#!/usr/bin/env python3
"""Fail-fast configuration loader (lesson OPS-250-L04). Standard library only.

Rules it demonstrates:
  * configuration comes from the environment (or a *_FILE path for secrets), never from code
  * every required value is checked at start-up; the program refuses to start with a clear list of problems
  * secrets are never printed: repr/str show only whether a secret is set and its length bucket
  * the same code runs in dev, test and prod; only the values differ

    APP_ENV=dev MAIL_API_BASE=http://127.0.0.1:8787 MAIL_API_TOKEN=local-demo-token python settings.py
    python settings.py demo         # shows the three cases: missing values, bad values, valid config
"""
import os
import sys
from urllib.parse import urlparse

SPEC = [  # name, required, kind, secret, default
    ("APP_ENV", True, "choice:dev|test|prod", False, None),
    ("MAIL_API_BASE", True, "url", False, None),
    ("MAIL_API_TOKEN", True, "str", True, None),
    ("LLM_BASE_URL", False, "url", False, "http://127.0.0.1:8787/v1"),
    ("LLM_API_KEY", False, "str", True, None),
    ("MAX_EMAILS_PER_RUN", False, "int:1..200", False, "20"),
]


class ConfigError(Exception):
    pass


class Secret(str):
    """A str that never shows its value when printed or logged."""
    def __repr__(self):
        return f"<secret set, {len(self)} chars>"
    __str__ = __repr__


def _raw(name, env):
    file_var = env.get(name + "_FILE")
    if file_var:  # Docker/Compose secrets convention: the value lives in a file, e.g. /run/secrets/<name>
        try:
            with open(file_var, encoding="utf-8") as f:
                return f.read().strip()
        except OSError as e:
            raise ConfigError(f"{name}_FILE points to an unreadable file ({e.__class__.__name__})") from None
    return env.get(name)


def load(env=None):
    env = os.environ if env is None else env
    cfg, problems = {}, []
    for name, required, kind, secret, default in SPEC:
        try:
            v = _raw(name, env)
        except ConfigError as e:
            problems.append(str(e)); continue
        if v in (None, ""):
            if required:
                problems.append(f"{name} is required"); continue
            v = default
            if v is None:
                cfg[name] = None; continue
        if kind == "url":
            u = urlparse(v)
            if u.scheme not in ("http", "https") or not u.netloc:
                problems.append(f"{name} must be an http(s) URL"); continue
        elif kind.startswith("choice:"):
            if v not in kind[7:].split("|"):
                problems.append(f"{name} must be one of {kind[7:]}"); continue
        elif kind.startswith("int:"):
            lo, hi = map(int, kind[4:].split(".."))
            if not v.isdigit() or not lo <= int(v) <= hi:
                problems.append(f"{name} must be an integer {lo}..{hi}"); continue
            v = int(v)
        cfg[name] = Secret(v) if secret else v
    if cfg.get("APP_ENV") == "prod" and str(cfg.get("MAIL_API_BASE") or "").startswith("http://"):
        problems.append("MAIL_API_BASE must use https in prod")
    if problems:
        raise ConfigError("; ".join(problems))
    return cfg


def demo():
    cases = {
        "missing values": {"APP_ENV": "dev"},
        "bad values": {"APP_ENV": "prod", "MAIL_API_BASE": "http://mail.example.com", "MAIL_API_TOKEN": "x",
                       "MAX_EMAILS_PER_RUN": "5000"},
        "valid dev config": {"APP_ENV": "dev", "MAIL_API_BASE": "http://127.0.0.1:8787",
                             "MAIL_API_TOKEN": "local-demo-token"},
    }
    for title, env in cases.items():
        try:
            print(f"{title:>17}: OK  {load(env)}")
        except ConfigError as e:
            print(f"{title:>17}: REFUSED TO START  {e}")


if __name__ == "__main__":
    if sys.argv[1:] == ["demo"]:
        demo()
    else:
        try:
            print(load())
        except ConfigError as e:
            sys.exit(f"configuration error: {e}")
