"""
payment_keys_service.py — the Stripe keys, editable from Settings → Sales by the Admin (client brief 2026-10-21,
sheet 2: "change the keys without going through the developer").

Rules from the brief, all enforced here and in admin.py:
  * encrypted in the database (Fernet, key = SECRETS_KEY or derived from ADMIN_JWT_SECRET), never returned in clear:
    the interface only gets `masked` ("••••3f2a", the last 4 characters) and `set`;
  * changed by typing the key again (an empty value in a PUT means "keep");
  * visible and editable by the Admin role only (admin.py), every change goes to the Journal;
  * a key saved here wins over the .env one. The .env stays the fallback, so an install that never opens this
    screen behaves exactly as before.
The publishable key is public by nature (the browser needs it to show the card form): `portal_public_key()` hands it
to the gallery, which used to need it baked into the frontend build (VITE_STRIPE_PUBLISHABLE_KEY).
"""
import base64
import hashlib
import logging
from typing import Optional

from cryptography.fernet import Fernet, InvalidToken

from core import config
from core.db import TABLE_OPTIONS, get_db
from core.security import jwt_secret
from core.timeutil import utcnow_iso

log = logging.getLogger("meeconic.payment_keys")

# name -> (label, required prefixes, the .env fallback)
KEYS: dict[str, tuple[tuple[str, ...], str]] = {
    "stripe_public_key":     (("pk_test_", "pk_live_"), "STRIPE_PUBLISHABLE_KEY"),
    "stripe_secret_key":     (("sk_test_", "sk_live_", "rk_test_", "rk_live_"), "STRIPE_SECRET_KEY"),
    "stripe_webhook_secret": (("whsec_",), "STRIPE_WEBHOOK_SECRET"),
}


class KeyError_(ValueError):
    pass


def init_table() -> None:
    with get_db() as conn:
        conn.execute(f"""
        CREATE TABLE IF NOT EXISTS app_secrets (
            name       VARCHAR(64) NOT NULL PRIMARY KEY,
            value_enc  MEDIUMTEXT  NOT NULL,
            updated_at VARCHAR(40) NOT NULL,
            updated_by VARCHAR(40)
        ) {TABLE_OPTIONS}""")
        conn.commit()


def _fernet() -> Fernet:
    seed = config.SECRETS_KEY or jwt_secret()
    return Fernet(base64.urlsafe_b64encode(hashlib.sha256(("secrets:" + seed).encode()).digest()))


def _env_value(name: str) -> str:
    # The .env values live in core.config (read once); STRIPE_PUBLISHABLE_KEY is new and read here.
    if name == "stripe_secret_key":
        return config.STRIPE_SECRET_KEY
    if name == "stripe_webhook_secret":
        return config.STRIPE_WEBHOOK_SECRET
    return config.STRIPE_PUBLISHABLE_KEY


def _stored(name: str) -> Optional[str]:
    try:
        with get_db() as conn:
            row = conn.execute("SELECT value_enc FROM app_secrets WHERE name=?", (name,)).fetchone()
    except Exception:
        return None            # table not created yet (very first start): the .env value applies
    if not row:
        return None
    try:
        return _fernet().decrypt(row["value_enc"].encode()).decode()
    except InvalidToken:
        # The encryption key changed (SECRETS_KEY / JWT secret rotated): never serve garbage as a key.
        log.error("Stored key %s cannot be decrypted — re-enter it in Settings → Sales.", name)
        return None


def get(name: str) -> str:
    """The key in use: the one saved in the interface, else the .env one, else ''."""
    return _stored(name) or _env_value(name) or ""


def stripe_secret() -> str:
    return get("stripe_secret_key")


def stripe_webhook_secret() -> str:
    return get("stripe_webhook_secret")


def portal_public_key() -> str:
    return get("stripe_public_key")


def _mask(value: str) -> str:
    return "••••" + value[-4:] if len(value) >= 8 else "••••"


def status() -> dict:
    """What the interface may know: whether each key is set, where from, and its last 4 characters. Never the key."""
    out: dict[str, dict] = {}
    for name in KEYS:
        stored = _stored(name)
        value = stored or _env_value(name)
        out[name] = {"set": bool(value), "masked": _mask(value) if value else "",
                     "source": "interface" if stored else ("env" if value else "")}
    return out


def _check(name: str, value: str) -> str:
    value = "".join((value or "").split())
    prefixes = KEYS[name][0]
    if not value.startswith(prefixes):
        raise KeyError_(f"{name}: must start with {' or '.join(prefixes)}.")
    if len(value) < 20 or len(value) > 400:
        raise KeyError_(f"{name}: that does not look like a complete key.")
    return value


def save(values: dict, by: str) -> list[str]:
    """Save the keys that were typed (non-empty). Returns their names. Nothing is saved if one is invalid."""
    clean = {}
    for name, raw in values.items():
        if name not in KEYS:
            raise KeyError_(f"Unknown key: {name}")
        if raw is None or not str(raw).strip():
            continue                                    # empty = keep the current one
        clean[name] = _check(name, str(raw))
    secret = clean.get("stripe_secret_key") or None
    public = clean.get("stripe_public_key") or None
    # test pk with live sk (or the reverse) cannot load a PaymentIntent: say it now, not at the first order.
    sk, pk = secret or stripe_secret(), public or portal_public_key()
    if sk and pk and (("_live_" in sk) != ("_live_" in pk)):
        raise KeyError_("The public key and the secret key are not from the same mode (test / live).")
    if clean:
        f, now = _fernet(), utcnow_iso()
        with get_db() as conn:
            for name, value in clean.items():
                conn.execute("INSERT OR REPLACE INTO app_secrets (name, value_enc, updated_at, updated_by) VALUES (?,?,?,?)",
                             (name, f.encrypt(value.encode()).decode(), now, by))
            conn.commit()
    return list(clean)


def test_connection() -> dict:
    """Ask Stripe who we are with the key in use. `ok` False carries a message that is safe to show."""
    import stripe
    sk = stripe_secret()
    if not sk:
        return {"ok": False, "message": "No secret key."}
    try:
        stripe.Balance.retrieve(api_key=sk)
    except stripe.AuthenticationError:
        return {"ok": False, "message": "Stripe refused this secret key."}
    except Exception as exc:                            # network, Stripe down…
        log.warning("Stripe connection test failed: %s", type(exc).__name__)
        return {"ok": False, "message": "Stripe could not be reached."}
    pk = portal_public_key()
    return {"ok": True, "mode": "live" if "_live_" in sk else "test", "public_key_set": bool(pk),
            "webhook_set": bool(stripe_webhook_secret())}
