"""Config loading for site-ng. Resolution per value (highest first):
  1. env var (NGSITE_DB_HOST, ...)
  2. config.ini [db]/[app] next to the project root (gitignored)
  3. built-in dev defaults (the local mirror DB on the Pi)

Dev points at the local mirror (arpartsfinder_dev / apfdev). Prod will
point at vdb1b with the READ-ONLY user (the site only reads).
"""

import configparser
import os
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent      # site-ng/
CONFIG_INI = ROOT / "config.ini"


def _ini() -> configparser.ConfigParser:
    cp = configparser.ConfigParser()
    if CONFIG_INI.exists():
        cp.read(CONFIG_INI)
    return cp


def _pick(env_key, ini, section, key, default):
    if os.environ.get(env_key):
        return os.environ[env_key]
    if ini.has_option(section, key):
        val = ini.get(section, key)
        if val and val != "changeme":
            return val
    return default


def load_config() -> dict:
    ini = _ini()
    return {
        # Dev defaults = the local mirror DB built by the scanner tee.
        "DB_HOST": _pick("NGSITE_DB_HOST", ini, "db", "host", "127.0.0.1"),
        "DB_PORT": int(_pick("NGSITE_DB_PORT", ini, "db", "port", "3306")),
        "DB_NAME": _pick("NGSITE_DB_NAME", ini, "db", "name",
                         "arpartsfinder_dev"),
        "DB_USER": _pick("NGSITE_DB_USER", ini, "db", "user", "apfdev"),
        "DB_PASSWORD": _pick("NGSITE_DB_PASSWORD", ini, "db", "password", ""),
        "NGSITE_ENV": _pick("NGSITE_ENV", ini, "app", "env", "dev"),
        # Google Analytics 4 measurement ID (e.g. G-XXXXXXXX). Empty = no
        # analytics. Set [app] ga_measurement_id in prod's config.ini to
        # enable; leave it unset on dev/staging so test traffic never hits
        # the live GA property.
        "GA_MEASUREMENT_ID": _pick("NGSITE_GA_ID", ini, "app",
                                   "ga_measurement_id", ""),
        # Flask session signing key. Required for the working-build cookie.
        # Empty here -> the app factory generates a random per-process key
        # (dev only, sessions invalidated on restart). For prod, set
        # [app] secret_key=<32+ hex bytes> in config.ini.
        "SECRET_KEY": _pick("NGSITE_SECRET_KEY", ini, "app", "secret_key", ""),
        # Absolute URL root used when building outbound URLs (magic-link
        # emails) without trusting the inbound request's Host: header.
        # Required in prod — see __init__.py's startup assertion. Empty
        # in dev = auth.py falls back to request.host_url (fine because
        # dev isn't reachable to attackers).
        "PUBLIC_URL_ROOT": _pick("NGSITE_PUBLIC_URL_ROOT", ini, "app",
                                 "public_url_root", ""),
        # Mail transport — see ngsite/mail.py for the list.
        #   console  : print to stdout (dev)
        #   file     : append to MAIL_FILE_PATH (staging — sshable file)
        #   sendmail : pipe to /usr/sbin/sendmail (prod option A)
        #   smtp     : connect to MAIL_SMTP_* (prod option B)
        "MAIL_TRANSPORT": _pick("NGSITE_MAIL_TRANSPORT", ini, "mail",
                                "transport", "console"),
        # File path for MAIL_TRANSPORT=file. Relative paths resolve
        # relative to the app root (parent of ngsite/). Outside the
        # web docroot — Apache won't serve it.
        "MAIL_FILE_PATH": _pick("NGSITE_MAIL_FILE_PATH", ini, "mail",
                                "file_path", "tmp/mail.log"),
        # From-address for outbound mail.
        "MAIL_FROM": _pick("NGSITE_MAIL_FROM", ini, "mail", "from_addr",
                           "noreply@arpartsfinder.com"),
        # SMTP transport config — only used when MAIL_TRANSPORT="smtp".
        # See ngsite/mail.py _send_smtp(). Empty defaults are fine when
        # the transport isn't SMTP; smtplib only opens a connection
        # when send_mail() is actually invoked.
        "MAIL_SMTP_HOST": _pick("NGSITE_MAIL_SMTP_HOST", ini, "mail",
                                "smtp_host", ""),
        "MAIL_SMTP_PORT": _pick("NGSITE_MAIL_SMTP_PORT", ini, "mail",
                                "smtp_port", "587"),
        "MAIL_SMTP_USER": _pick("NGSITE_MAIL_SMTP_USER", ini, "mail",
                                "smtp_user", ""),
        "MAIL_SMTP_PASSWORD": _pick("NGSITE_MAIL_SMTP_PASSWORD", ini,
                                    "mail", "smtp_password", ""),
        # "1" = STARTTLS on a 587 submission (the standard); "0" = plain.
        "MAIL_SMTP_TLS": _pick("NGSITE_MAIL_SMTP_TLS", ini, "mail",
                               "smtp_tls", "1"),
    }
