"""
Key issuance — turns a paid subscription into a signed biosync license key.

The Ed25519 PRIVATE key lives only here (the billing server). It must never ship
in the app. Source it from the BIOSYNC_LICENSE_PRIVKEY environment variable in
production; for local dev it falls back to license_server/private_key.hex.
"""

from __future__ import annotations

import os
import uuid
from datetime import date, timedelta
from pathlib import Path

from biosync.licensing import sign_key

_DEV_KEYFILE = Path(__file__).with_name("private_key.hex")

PLANS = {
    # plan -> (days, price_in_cents, currency, label, period)
    # Annual: R300,000 / year.  Monthly: R25,000 / month via debit order
    # (35-day key gives a grace buffer; renew on each successful monthly debit).
    "annual": (365, 30_000_000, "ZAR", "Annual subscription", "year"),
    "monthly": (35, 2_500_000, "ZAR", "Monthly debit order", "month"),
}


def private_key_hex() -> str:
    env = os.environ.get("BIOSYNC_LICENSE_PRIVKEY")
    if env:
        return env.strip()
    if _DEV_KEYFILE.exists():
        return _DEV_KEYFILE.read_text().strip()
    raise RuntimeError(
        "No signing key. Set BIOSYNC_LICENSE_PRIVKEY or create private_key.hex")


def issue_license(email: str, plan: str = "annual", days: int | None = None) -> dict:
    days = days if days is not None else PLANS.get(plan, PLANS["annual"])[0]
    license_id = "LIC-" + uuid.uuid4().hex[:10].upper()
    key = sign_key(private_key_hex(), email=email, plan=plan, days=days,
                   license_id=license_id)
    issued = date.today()
    return {"license_id": license_id, "key": key, "plan": plan,
            "issued": issued.isoformat(),
            "expires": (issued + timedelta(days=days)).isoformat()}
