"""Conservative, resumable bulk crest assignment for the existing team registry.

Does NOT alter SoccerRating crest discovery. Assigns only API-Football
metadata-confirmed, unambiguous senior-team crests; preserves saved logos.
Run --dry-run first; --apply explicitly enables additive changes.
"""
from __future__ import annotations

import argparse
import collections
from concurrent.futures import ThreadPoolExecutor
from contextlib import closing
import datetime as dt
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import sqlite3
import sys
import time
from urllib.parse import urlsplit

ROOT = Path(__file__).resolve().parent
REG = ROOT / "team_identity_registry.db"
MAIN = ROOT / "football_analytics.db"
LOGOS = ROOT / "team_logos"
from fa_backup_paths import backup_root
BACKUPS = backup_root(ROOT)

import team_identity_registry as teams
import sr_logo_discovery as discovery
import team_crest_safe_writer as safe_writer


def key(name):
    return re.sub(r"\s+", " ", str(name or "").strip()).casefold()


def backup_before_write():
    stamp = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%d_%H%M%S")
    folder = BACKUPS / ("team_identity_crest_backfill_" + stamp)
    folder.mkdir(parents=True, exist_ok=False)
    for source in (REG, MAIN):
        src = sqlite3.connect(str(source))
        dst = sqlite3.connect(str(folder / source.name))
        try:
            src.backup(dst)
        finally:
            dst.close()
            src.close()
    if LOGOS.is_dir():
        shutil.copytree(LOGOS, folder / "team_logos")
    return folder


def existing_ids_and_names():
    with closing(sqlite3.connect(str(REG))) as db:
        all_teams = db.execute(
            "SELECT team_id, canonical_name, country, category, gender FROM teams"
        ).fetchall()
        counts = collections.Counter(key(t[1]) for t in all_teams)
        by_id = {r[0]: r for r in all_teams}
        scores = dict(db.execute(
            "SELECT name_key, COUNT(*) FROM name_observations GROUP BY name_key"
        ).fetchall())
        ids = db.execute(
            "SELECT team_id, external_id FROM provider_ids WHERE provider=?",
            ("api_football",)
        ).fetchall()
        crest_table = db.execute(
            "SELECT 1 FROM sqlite_master WHERE type='table' AND name='team_crests'"
        ).fetchone()
        already = set()
        if crest_table:
            already = {r[0] for r in db.execute("SELECT team_id FROM team_crests")}
        rejected_table = db.execute(
            "SELECT 1 FROM sqlite_master WHERE type='table' AND name='team_crest_rejections'"
        ).fetchone()
        rejected_ids = ({r[0] for r in db.execute("SELECT team_id FROM team_crest_rejections")}
                        if rejected_table else set())
        quarantine_table = db.execute(
            "SELECT 1 FROM sqlite_master WHERE type='table' AND name='team_crest_quarantine'"
        ).fetchone()
        quarantined_ids = ({r[0] for r in db.execute("SELECT team_id FROM team_crest_quarantine")}
                           if quarantine_table else set())
    with closing(sqlite3.connect(str(MAIN))) as db:
        used = {r[0] for r in db.execute("SELECT team_key FROM team_logos")}
        # A global legacy name cache could mislabel a match in another country.
        # Exclude names used with conflicting, nonblank historical match countries.
        name_countries = collections.defaultdict(set)
        for home, away, observed_country in db.execute("SELECT home,away,country FROM matches"):
            c = teams._country(observed_country)
            if not c:
                continue
            name_countries[key(home)].add(c)
            name_countries[key(away)].add(c)
    targets = []
    for team_id, provider_id in ids:
        t = by_id.get(team_id)
        if not t or not str(provider_id).isdigit():
            continue
        _, name, country, category, gender = t
        k = key(name)
        if (not country or not k or counts[k] != 1 or k in used
                or team_id in already or team_id in rejected_ids or team_id in quarantined_ids
                or any(c != teams._country(country) for c in name_countries.get(k, set()))):
            continue
        if teams._class(name, category, gender):
            continue
        targets.append((team_id, name, country, str(provider_id), scores.get(teams.norm(name), 0)))
    targets.sort(key=lambda t: (-t[4], t[1].casefold()))
    return len(all_teams), len(ids), targets


def source_linked_short_alias(team_name, country, provider_id, provider_name):
    """Allow only a registry-recorded provider abbreviation with no rival senior claim.

    This authorizes crest artwork only; it NEVER promotes fixture aliases or votes.
    Reep ID bridge, country, canonical name and alias must all agree.
    """
    short = teams.norm(provider_name)
    full = teams.norm(team_name)
    if len(short) < 5 or short == full or not full.startswith(short + " "):
        return False
    with closing(sqlite3.connect(str(REG))) as db:
        bridges = db.execute(
            """SELECT DISTINCT t.team_id,t.canonical_name,t.country,t.category,t.gender
                 FROM provider_ids p JOIN teams t ON t.team_id=p.team_id
                 WHERE p.provider='api_football' AND p.external_id=?""",
            (provider_id,)
        ).fetchall()
        if len(bridges) != 1:
            return False
        team_id, canonical, reg_country, category, gender = bridges[0]
        if (teams.norm(canonical) != teams.norm(team_name)
                or teams._country(reg_country) != teams._country(country)
                or teams._class(canonical, category, gender)):
            return False
        # Claimed aliases can be proposed, but they must match this provider
        # label AND must not be claimed by a different senior team locally.
        claims = db.execute(
            """SELECT DISTINCT t.team_id,t.canonical_name,t.country,t.category,t.gender
                 FROM aliases a JOIN teams t ON t.team_id=a.team_id
                 WHERE a.name_key=? LIMIT 101""", (short,)
        ).fetchall()
        if len(claims) >= 101 or not any(r[0] == team_id for r in claims):
            return False
        for rid, rival, rival_country, rival_category, rival_gender in claims:
            if teams._country(rival_country) != teams._country(country):
                continue
            if teams._class(rival, rival_category, rival_gender):
                continue  # A women's or youth team is a different identity.
            if rid != team_id and not discovery.names_match(team_name, rival):
                return False  # Unrelated senior or similarly named team.
    return True


def fetch_verified_asset(team_name, country, provider_id, record=None):
    if record is None:
        payload = discovery.api_football_request(
            "teams", {"id": provider_id}, ttl=24 * 3600
        )
        records = payload.get("response") or []
    else:
        records = [record]
    if len(records) != 1:
        raise ValueError("Provider ID not resolved to exactly one team")
    info = records[0].get("team") or {}
    actual_id = str(info.get("id") or "")
    actual_name = str(info.get("name") or "")
    actual_country = str(info.get("country") or "")
    if actual_id != provider_id:
        raise ValueError("Provider returned a different team ID")
    if (not discovery.names_match(team_name, actual_name)
            and not source_linked_short_alias(team_name, country, provider_id, actual_name)):
        raise ValueError("Canonical name and provider team name disagree")
    if not country or not actual_country or teams._country(country) != teams._country(actual_country):
        raise ValueError("Country identity conflict or missing country")
    if teams._class(team_name) != teams._class(actual_name):
        raise ValueError("Different team category or gender")
    image = str(info.get("logo") or "")
    parts = urlsplit(image)
    if (parts.scheme != "https" or parts.hostname != "media.api-sports.io"
            or parts.path != "/football/teams/" + provider_id + ".png"
            or parts.query or parts.fragment):
        raise ValueError("Provider image URL does not match its team ID")
    raw = discovery.retrieve(image)
    if len(raw) < 650 or not raw.startswith(bytes.fromhex("89504e470d0a1a0a")):
        raise ValueError("No valid PNG crest was returned")
    # Reject invalid, very small or implausibly shaped provider artwork.
    # Pillow is already used by the app's existing crest discovery.
    from PIL import Image, UnidentifiedImageError
    import io
    try:
        with Image.open(io.BytesIO(raw)) as pict:
            pict.verify()
        with Image.open(io.BytesIO(raw)) as pict:
            width, height = pict.size
            if not (48 <= width <= 2048 and 48 <= height <= 2048):
                raise ValueError("Suspicious crest image dimensions")
            if max(width, height) / min(width, height) > 4:
                raise ValueError("Suspicious crest aspect ratio")
    except (UnidentifiedImageError, OSError) as exc:
        raise ValueError("Invalid image bytes") from exc
    artwork_digest = hashlib.sha256(raw).hexdigest()
    with closing(sqlite3.connect(str(REG))) as db:
        quarantine_exists = db.execute(
            "SELECT 1 FROM sqlite_master WHERE type='table' AND name='team_crest_quarantine'"
        ).fetchone()
        if quarantine_exists and db.execute(
            "SELECT 1 FROM team_crest_quarantine WHERE sha256=? LIMIT 1",
            (artwork_digest,)
        ).fetchone():
            raise ValueError("Provider artwork matches a quarantined reused image")
    return raw, actual_name, actual_country, image


def save_identity_country_snapshot(country, records):
    """Export already-fetched provider IDs for offline identity verification.

    No credentials, fixture votes, artwork or importer state are included.
    A malformed snapshot must never be mistaken for an authoritative source.
    """
    folder = ROOT.parent.parent / "FootballAnalytics_Diagnostics" / "CREST_PROVIDER_SNAPSHOTS"
    folder.mkdir(parents=True, exist_ok=True)
    country_key = teams._country(country)
    digest = hashlib.sha256(country_key.encode("utf-8")).hexdigest()[:16]
    items = []
    for entry in records:
        info = entry.get("team") or {}
        if str(info.get("id") or "").isdigit():
            items.append({"id": str(info["id"]), "name": str(info.get("name") or ""),
                          "country": str(info.get("country") or ""),
                          "national": bool(info.get("national"))})
    if len(items) != len(records):
        raise ValueError("Incomplete provider IDs; skip identity linking for this country")
    blob = json.dumps(items, ensure_ascii=False, sort_keys=True)
    result = {"source": "api_football_country_teams", "version": 1,
              "country": country, "country_key": country_key,
              "obtained_at": int(time.time()), "response_count": len(records),
              "metadata_sha256": hashlib.sha256(blob.encode("utf-8")).hexdigest(),
              "teams": items}
    path = folder / (digest + ".json")
    tmp = folder / (digest + ".json.tmp")
    tmp.write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
    os.replace(tmp, path)
    print("IDENTITY_SOURCE_SNAPSHOT", str(path), flush=True)


def write_assignment(team_id, name, country, provider_id, result):
    """Validated artwork; recoverable one-database-at-a-time writes.

    Do not use an ATTACH write spanning the app WAL database and registry
    DELETE-mode database: such a transaction is not crash-atomic.
    """
    return safe_writer.assign(
        MAIN, REG, LOGOS, team_id, name, country, provider_id, result, key
    )


def record_rejection(team_id, provider_id, reason):
    with closing(safe_writer.connect(REG)) as db:
        safe_writer.begin_immediate(db)
        db.execute("""CREATE TABLE IF NOT EXISTS team_crest_rejections (
            team_id TEXT PRIMARY KEY REFERENCES teams(team_id),
            provider_id TEXT NOT NULL,
            reason TEXT NOT NULL,
            checked_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
        )""")
        db.execute("""INSERT INTO team_crest_rejections(team_id,provider_id,reason)
                      VALUES(?,?,?) ON CONFLICT(team_id)
                      DO UPDATE SET provider_id=excluded.provider_id,
                                    reason=excluded.reason,
                                    checked_at=CURRENT_TIMESTAMP""",
                   (team_id, provider_id, reason[:300]))
        db.commit()


def main():
    # Windows PowerShell's legacy cp1252 console cannot render every Unicode
    # team name. Logging must never turn a successful assignment into a
    # spurious rejection after a committed database write.
    if hasattr(sys.stdout, "reconfigure"):
        sys.stdout.reconfigure(errors="backslashreplace")
    p = argparse.ArgumentParser()
    p.add_argument("--apply", action="store_true", help="Write only verified, additive mappings")
    p.add_argument("--limit", type=int, default=5, help="Maximum API identity checks in this run")
    p.add_argument("--country", default="", help="Limit to one registry country")
    p.add_argument("--group-country", action="store_true",
                   help="Retrieve all provider country teams in one guarded request")
    p.add_argument("--workers", type=int, default=1,
                   help="At most 3 parallel image fetches; writes remain serialized")
    p.add_argument("--repair-only", action="store_true",
                   help="With --apply, reconcile incomplete registry-to-display mappings")
    a = p.parse_args()
    if not 1 <= a.limit <= 200:
        p.error("--limit must be between 1 and 200")
    if a.group_country and not a.country:
        p.error("--group-country requires --country")
    if not 1 <= a.workers <= 3:
        p.error("--workers must be between 1 and 3")
    if a.workers > 1 and not a.group_country:
        p.error("Parallel fetching requires --group-country")
    if a.repair_only:
        if not a.apply:
            p.error("--repair-only requires --apply")
        backup = backup_before_write()
        print("RECOVERY_BACKUP", str(backup), flush=True)
        restored = safe_writer.repair_pending(MAIN, REG, LOGOS, key)
        print("PROJECTION_REPAIR", json.dumps({"restored": restored,
                "count": len(restored)}, ensure_ascii=True), flush=True)
        return
    total, bridged, pending = existing_ids_and_names()
    if a.country:
        pending = [r for r in pending if teams._country(r[2]) == teams._country(a.country)]
    print(json.dumps({"registered_teams": total, "api_football_id_bridges": bridged,
                      "unambiguous_missing_crest_candidates": len(pending),
                      "mode": "apply" if a.apply else "dry_run",
                      "sample": [{"team": r[1], "country": r[2], "id": r[3], "observed": r[4]}
                                 for r in pending[:min(a.limit, 8)]]}, ensure_ascii=True))
    if not a.apply:
        return
    if not pending:
        print("No eligible teams remain")
        return
    if not discovery.api_football_key():
        raise RuntimeError("API-Football verification key unavailable; no changes made")
    by_provider_id = {}
    if a.group_country:
        try:
            payload = discovery.api_football_request(
                "teams", {"country": a.country}, ttl=24 * 3600
            )
            items = payload.get("response") or []
            if not items:
                raise ValueError("Country provider response empty; no assignment is safe")
            for item in items:
                info = item.get("team") or {}
                pid = str(info.get("id") or "")
                if pid.isdigit():
                    if pid in by_provider_id:
                        raise ValueError("Duplicate provider team ID in country response")
                    by_provider_id[pid] = item
            print("COUNTRY_SOURCE", json.dumps({"country": a.country,
                   "provider_teams": len(by_provider_id)}, ensure_ascii=True), flush=True)
            try:
                save_identity_country_snapshot(a.country, items)
            except (OSError, ValueError, TypeError) as snap_exc:
                print("IDENTITY_SNAPSHOT_UNAVAILABLE", type(snap_exc).__name__, flush=True)
        except Exception as exc:
            print("PROVIDER_UNAVAILABLE", type(exc).__name__ + ": " + str(exc)[:200])
            return
    backup = backup_before_write()
    print("RECOVERY_BACKUP", backup, flush=True)
    restored = safe_writer.repair_pending(MAIN, REG, LOGOS, key)
    if restored:
        print("PROJECTION_REPAIR", json.dumps({"restored": restored,
               "count": len(restored)}, ensure_ascii=True), flush=True)
    saved, rejected, unavailable, blocked = [], [], [], None
    selected = pending[:a.limit]

    def prepare(row):
        team_id, name, country, provider_id, _ = row
        if a.group_country and provider_id not in by_provider_id:
            return ("unavailable", None)
        try:
            result = fetch_verified_asset(
                name, country, provider_id,
                by_provider_id[provider_id] if a.group_country else None
            )
            return ("ok", result)
        except Exception as exc:
            return ("error", exc)

    # Download/read-only verification may overlap, but database/image writes
    # are always one-at-a-time in the main thread.
    with ThreadPoolExecutor(max_workers=a.workers) as pool:
        for row, prepared in zip(selected, pool.map(prepare, selected)):
            team_id, name, country, provider_id, _ = row
            state, value = prepared
            if state == "unavailable":
                unavailable.append(name)
                continue
            try:
                if state == "error":
                    raise value
                write_assignment(team_id, name, country, provider_id, value)
                saved.append(name)
                print("ASSIGNED", name, provider_id, flush=True)
            except RuntimeError as exc:
                blocked = str(exc)
                break
            except sqlite3.Error as exc:
                # Fail closed on ANY SQLite write/read error. Continuing could
                # compound a partial database or filesystem commit.
                blocked = ("SQLite failure [" + str(getattr(exc, "sqlite_errorname", "UNKNOWN"))
                           + "]: " + str(exc)[:220])
                print("SQLITE_WRITE_BLOCKER", blocked, flush=True)
                break
            except ValueError as exc:
                if str(exc).startswith("API-Football:"):
                    blocked = "Temporary provider response: " + str(exc)[:160]
                    break
                try:
                    record_rejection(team_id, provider_id, str(exc))
                except sqlite3.Error as write_exc:
                    blocked = ("SQLite failure [" + str(getattr(write_exc,"sqlite_errorname","UNKNOWN"))
                               + "]: " + str(write_exc)[:220])
                    print("SQLITE_WRITE_BLOCKER",blocked,flush=True)
                    break
                rejected.append({"team": name, "reason": "ValueError: " + str(exc)[:130]})
            except Exception as exc:
                # Network and local I/O errors are retryable, not identity rejections.
                # Preserve extended SQLite error codes to diagnose intermittent Windows I/O.
                detail = type(exc).__name__ + ": " + str(exc)[:130]
                sqlite_code = getattr(exc, "sqlite_errorname", None)
                if sqlite_code:
                    detail += " [" + sqlite_code + "]"
                rejected.append({"team": name, "reason": detail})
    with closing(sqlite3.connect(str(MAIN))) as db:
        main_ok = db.execute("PRAGMA quick_check").fetchone()[0]
        count = db.execute("SELECT COUNT(*) FROM team_logos").fetchone()[0]
        matches = db.execute("SELECT COUNT(*) FROM matches").fetchone()[0]
    with closing(sqlite3.connect(str(REG))) as db:
        reg_ok = db.execute("PRAGMA quick_check").fetchone()[0]
        total_assignments = db.execute("SELECT COUNT(*) FROM team_crests").fetchone()[0]
    print("RESULT", json.dumps({"assigned": saved, "rejected": rejected,
             "provider_not_in_country_result": unavailable,
             "provider_blocker": blocked, "main_quick_check": main_ok,
             "registry_quick_check": reg_ok, "main_logo_count": count,
             "identity_crest_count": total_assignments, "match_count": matches,
             "backup": str(backup)}, ensure_ascii=True))


if __name__ == "__main__":
    main()
