"""Convert docs/ato-master/ato-master-10nov.json into generator page records.

Does not invent paid or verified status, and does not copy or invent reviews (REV-022). Base links use /ad/{CODE}
(ATO-19). A missing code stays plain text and is flagged. A school with no name uses the certificate digits only.

One school, one slug (REV-023):
  * Two different schools that end up with the same slug STOP the conversion. (They used to overwrite each other.)
  * Schools that really are one school under several names are merged ONLY when they are in MERGES, by exact
    school_id or exact slug. A name that merely contains "skyhawk" is no longer swept into Aeronav.
The slug rule here is the same one the database seed uses (tools/reviews/seed_from_master.mjs); both are tested
against tools/reviews/slug_cases.json.
"""
from __future__ import annotations

import json
import re
import unicodedata
from datetime import date
from pathlib import Path

SLUG_RE = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
CODE_RE = re.compile(r"^[A-Z0-9-]{3,8}$")
# One page for several names. Key = the page slug. Values = exact school_id or exact slug. Confirm against the master.
MERGES = {
    "aeronav-academy": ("aeronav-academy", "aeronav", "skyhawk", "skyhawk-aviation", "excellentia", "excellentia-airline-academy"),
}


def cert_digits(approval_id: str | None) -> str | None:
    m = re.search(r"(\d+)", approval_id or "")
    return m.group(1) if m else None


def slugify_name(name: str) -> str:
    """Lower case; accents dropped (é -> e); every run of other characters becomes one hyphen."""
    s = unicodedata.normalize("NFKD", name or "")
    s = "".join(ch for ch in s if not unicodedata.combining(ch)).lower()
    return re.sub(r"[^a-z0-9]+", "-", s).strip("-")


def _name(school: dict) -> str:
    return (school.get("trading_name") or school.get("official_name") or "").strip()


def school_slug(school: dict) -> str:
    keys = {str(k).lower() for k in (school.get("school_id"), school.get("slug"), slugify_name(_name(school))) if k}
    for target, members in MERGES.items():
        if keys & set(members):
            return target
    name = _name(school)
    if name:
        slug = school.get("slug")
        if slug and SLUG_RE.match(slug):
            return slug
        return slugify_name(name)
    for ap in school.get("approvals") or []:
        digits = cert_digits(ap.get("approval_id"))
        if digits:
            return digits
    return slugify_name(school.get("school_id") or "")


def first_approval_id(school: dict) -> str:
    approvals = school.get("approvals") or []
    for ap in approvals:
        if str(ap.get("status") or "").lower() == "valid" and ap.get("approval_id"):
            return ap["approval_id"]
    if approvals and approvals[0].get("approval_id"):
        return approvals[0]["approval_id"]
    return school.get("school_id") or school_slug(school)


def pick_contact(school: dict) -> dict:
    """Raw values only. generator.check() validates them and leaves out anything that is not a plain value."""
    phone = school.get("phone") or {}
    email = school.get("email") or {}
    website = school.get("website") or {}
    web = (website.get("url") or website.get("host")) if isinstance(website, dict) else website
    if web:
        web = re.sub(r"^https?://", "", str(web), flags=re.I).rstrip("/")
    return {
        "phone": phone.get("number") if isinstance(phone, dict) else phone,
        "email": email.get("address") if isinstance(email, dict) else email,
        "web": web or None,
    }


def _iso(value, what, who, warnings):
    if not value:
        return None
    try:
        return date.fromisoformat(str(value)).isoformat()
    except ValueError:
        warnings.append(f"{who}: {what} {value!r} is not a date; left out")
        return None


def convert_school(school: dict, today: date) -> dict:
    who = school.get("school_id") or "?"
    warnings = []
    bases = []
    for ap in school.get("approvals") or []:
        b = ap.get("base") or {}
        ident = b.get("ident")
        if ident and not CODE_RE.match(str(ident)):
            warnings.append(f"{who}: aerodrome code {ident!r} is not valid; base shown as plain text")
            ident = None
        href = f"/ad/{ident}" if ident else None
        name = b.get("name") or b.get("aerodrome") or b.get("town") or ident or ""
        town = b.get("town")
        if not ident:
            warnings.append(f"{who}: missing aerodrome code for {name or ap.get('approval_id')}")
        expiry = _iso(ap.get("expiry"), "expiry", who, warnings)
        cert = {
            "number": ap.get("approval_id"),
            "valid_until": expiry,
            "updated": _iso(ap.get("updated"), "updated date", who, warnings),
        }
        if expiry:
            # Current/Expired from the expiry date, never the ATP `current` flag.
            cert["current"] = date.fromisoformat(expiry) >= today
        bases.append({
            "ident": ident,
            "name": name,
            "town": town,
            "href": href,
            "anchor": slugify_name(str(b.get("anchor") or ident or town or cert_digits(ap.get("approval_id")) or "base")) or "base",
            "certificate": cert,
        })
    about = school.get("about")
    about_text = about.get("text") if isinstance(about, dict) else about
    courses = []
    for c in school.get("courses") or []:
        if isinstance(c, str):
            courses.append(c)
        elif isinstance(c, dict) and c.get("name"):
            courses.append(c["name"])
    rec = {
        "id": first_approval_id(school),
        "slug": school_slug(school),
        "name": _name(school) or ("ATO " + (cert_digits(first_approval_id(school)) or school_slug(school))),
        "handle": school.get("handle"),
        "kind": school.get("kind"),
        "bases": bases,
        "about": about_text,
        "contact": pick_contact(school),
        "courses": courses,
        "top_reviews": [],
        "legacy_slug_targets": school.get("legacy_slug_targets") or [],
        "_warnings": warnings,
        "_school_id": school.get("school_id"),
    }
    # Do not invent paid or verified.
    if school.get("status") in ("paid", "verified", "unclaimed", "gifted", "lapsed"):
        rec["status"] = school["status"]
    return rec


def _merge(main: dict, other: dict) -> dict:
    """Two master entries that are ONE school (in MERGES): one page that keeps every certificate and course."""
    if slugify_name(other["name"]) == main["slug"] and slugify_name(main["name"]) != main["slug"]:
        main, other = other, main                       # the entry carrying the page's own name leads
    have = {(b.get("certificate") or {}).get("number") for b in main["bases"]}
    main["bases"] += [b for b in other["bases"] if (b.get("certificate") or {}).get("number") not in have]
    main["courses"] += [c for c in other["courses"] if c not in main["courses"]]
    main["_warnings"] += other["_warnings"]
    main["_merged_from"] = (main.get("_merged_from") or [main["_school_id"]]) + (other.get("_merged_from") or [other["_school_id"]])
    for k in ("about", "handle", "status"):
        if not main.get(k) and other.get(k):
            main[k] = other[k]
    return main


def _unique_anchors(rec: dict) -> None:
    seen = set()
    for i, b in enumerate(rec["bases"]):
        a = b["anchor"]
        if a in seen:
            a = f"{a}-{cert_digits((b.get('certificate') or {}).get('number')) or i}"
        seen.add(a)
        b["anchor"] = a


def convert_master(master, today: date) -> list[dict]:
    if isinstance(master, (str, Path)):
        master = json.loads(Path(master).read_text())
    recs: dict[str, dict] = {}
    for s in master.get("schools") or []:
        rec = convert_school(s, today)
        slug = rec["slug"]
        if not SLUG_RE.match(slug or ""):
            raise ValueError(f"REV-023: bad slug {slug!r} for school {s.get('school_id')}")
        if slug in recs:
            if slug not in MERGES:
                raise ValueError(f"REV-023: slug {slug!r} is used by both {recs[slug]['_school_id']} and {s.get('school_id')}. "
                                 "Fix the master, or add them to MERGES if they are one school.")
            recs[slug] = _merge(recs[slug], rec)
        else:
            recs[slug] = rec
    for rec in recs.values():
        _unique_anchors(rec)
    return list(recs.values())


def convert_master_to_dir(master_path, out_dir: Path, today: date) -> Path:
    out_dir = Path(out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    for old in out_dir.glob("*.json"):                  # this folder is generated; no page may survive from an older master
        old.unlink()
    warnings = []
    for rec in convert_master(master_path, today):
        warnings.extend(rec.get("_warnings") or [])
        dest = out_dir / f"{rec['slug']}.json"          # slug already matched SLUG_RE, so it cannot leave the folder
        dest.write_text(json.dumps(rec, indent=2, ensure_ascii=False) + "\n")
    (out_dir / "_warnings.json").write_text(json.dumps(warnings, indent=2) + "\n")
    return out_dir
