"""Crash-recoverable two-database projection for team crest backfills.

The active app's WAL database is never switched to DELETE mode.
Registry mapping is committed first, then the legacy display cache.
If the display write fails, compensate the mapping; if interrupted, a
subsequent repair can safely finish the projection. The two files are
NOT one crash-atomic SQLite transaction.
"""
from __future__ import annotations

from contextlib import closing
import hashlib
import os
from pathlib import Path
import sqlite3
import time


class DiagnosticConnection(sqlite3.Connection):
    """Tag SQLite errors with the failed database and SQL (never bound values).

    Preserve SQLite's original exception type and extended sqlite_errorcode.
    This does not change SQL execution, transaction order, or retry policy.
    """

    def execute(self, sql, parameters=(), /):
        try:
            return super().execute(sql, parameters)
        except sqlite3.Error as exc:
            statement = " ".join(str(sql).split())[:120]
            database = getattr(self, "_diagnostic_database", "unknown")
            exc.args = (f"{exc} [database={database}; statement={statement}]",)
            raise


def connect(path):
    label = Path(path).name
    try:
        db = sqlite3.connect(
            str(path), timeout=30, isolation_level=None, factory=DiagnosticConnection
        )
    except sqlite3.Error as exc:
        exc.args = (f"{exc} [database={label}; statement=CONNECT]",)
        raise
    db._diagnostic_database = label
    try:
        db.execute("PRAGMA busy_timeout=30000")
    except Exception:
        db.close()
        raise
    return db


def begin_immediate(db):
    """Retry only a failed transaction start, never an uncertain write/COMMIT."""
    for attempt in range(2):
        try:
            return db.execute("BEGIN IMMEDIATE")
        except sqlite3.OperationalError as exc:
            if (attempt or db.in_transaction
                    or getattr(exc,"sqlite_errorname","") not in
                    ("SQLITE_BUSY","SQLITE_BUSY_RECOVERY","SQLITE_BUSY_TIMEOUT")):
                raise
            time.sleep(1.0)


def active_crest(db, team_id):
    return db.execute(
        "SELECT filename,sha256 FROM team_crests WHERE team_id=?", (team_id,)
    ).fetchone()


def has_quarantined_hash(db, sha):
    table = db.execute(
        "SELECT 1 FROM sqlite_master WHERE type='table' AND name='team_crest_quarantine'"
    ).fetchone()
    return bool(table and db.execute(
        "SELECT 1 FROM team_crest_quarantine WHERE sha256=? LIMIT 1", (sha,)
    ).fetchone())


def main_has_exact(main_path, team_key, filename):
    with closing(connect(main_path)) as db:
        return bool(db.execute(
            "SELECT 1 FROM team_logos WHERE team_key=? AND filename=?",
            (team_key, filename)
        ).fetchone())


def assign(main_path, registry_path, logos_dir, team_id, name, country,
           provider_id, result, key_fn, *, _test_failure_after_registry=False):
    raw, actual_name, actual_country, url = result
    k = key_fn(name)
    sha = hashlib.sha256(raw).hexdigest()
    filename = hashlib.sha256(k.encode("utf-8")).hexdigest()[:16] + ".png"
    logo_dir = Path(logos_dir)
    logo_dir.mkdir(parents=True, exist_ok=True)
    target = logo_dir / filename
    if target.exists():
        raise ValueError("A file for this team name already exists")
    with closing(connect(main_path)) as db:
        if db.execute("SELECT 1 FROM team_logos WHERE team_key=?", (k,)).fetchone():
            raise ValueError("A saved logo already uses this team name")

    temp = target.with_suffix(".png.tmp")
    temp.write_bytes(raw)
    os.replace(temp, target)

    committed_registry = False
    try:
        with closing(connect(registry_path)) as db:
            begin_immediate(db)
            try:
                if active_crest(db, team_id):
                    raise ValueError("Registry team already has a crest")
                if db.execute(
                    "SELECT 1 FROM team_crests WHERE sha256=? LIMIT 1", (sha,)
                ).fetchone():
                    raise ValueError("Identical crest artwork already assigned to another team")
                if has_quarantined_hash(db, sha):
                    raise ValueError("Provider image matches quarantined reused artwork")
                qtable = db.execute(
                    "SELECT 1 FROM sqlite_master WHERE type='table' AND name='team_crest_quarantine'"
                ).fetchone()
                if qtable and db.execute(
                    "SELECT 1 FROM team_crest_quarantine WHERE team_id=?", (team_id,)
                ).fetchone():
                    raise ValueError("Registry team remains quarantined")
                db.execute(
                    """INSERT INTO team_crests
                    (team_id,provider,provider_id,canonical_name,provider_name,
                     verified_country,filename,sha256,evidence_url,status)
                    VALUES(?,?,?,?,?,?,?,?,?,?)""",
                    (team_id, "API-Football", provider_id, name, actual_name,
                     actual_country, filename, sha, url, "verified")
                )
                db.execute("COMMIT")
                committed_registry = True
            except Exception:
                db.rollback()
                raise

        if _test_failure_after_registry:
            raise sqlite3.OperationalError("simulated failure after registry COMMIT")

        with closing(connect(main_path)) as db:
            begin_immediate(db)
            try:
                if db.execute(
                    "SELECT 1 FROM team_logos WHERE team_key=?", (k,)
                ).fetchone():
                    raise ValueError("Saved logo appeared while backfill was running")
                db.execute(
                    "INSERT INTO team_logos(team_key,team_name,filename,mime_type) VALUES(?,?,?,?)",
                    (k,name,filename,"image/png")
                )
                db.execute("COMMIT")
            except Exception:
                db.rollback()
                raise
    except Exception as original:
        # A COMMIT can occasionally report an I/O failure despite a durable
        # write. Observe the display cache before attempting compensation.
        if main_has_exact(main_path,k,filename):
            return
        if committed_registry:
            try:
                with closing(connect(registry_path)) as db:
                    begin_immediate(db)
                    try:
                        removed = db.execute(
                            "DELETE FROM team_crests WHERE team_id=? AND filename=? AND sha256=?",
                            (team_id,filename,sha)
                        ).rowcount
                        if removed != 1:
                            raise RuntimeError("Registry compensation record changed")
                        db.execute("COMMIT")
                    except Exception:
                        db.rollback()
                        raise
            except Exception as cleanup:
                raise RuntimeError(
                    "Crest registry projection incomplete; run safe repair before continuing: "
                    + str(cleanup)
                ) from original
        # Only delete the new image if neither database references it.
        with closing(connect(registry_path)) as db:
            referenced = bool(active_crest(db,team_id))
        if not referenced and not main_has_exact(main_path,k,filename):
            target.unlink(missing_ok=True)
        raise


def repair_pending(main_path, registry_path, logos_dir, key_fn):
    """Idempotently repair a registry-only mapping after a process interruption.

    Never overwrite a manually assigned or conflicting display logo.
    Never revive quarantined artwork or an asset whose bytes changed.
    """
    repaired = []
    with closing(connect(registry_path)) as db:
        entries = db.execute(
            "SELECT team_id,canonical_name,filename,sha256 FROM team_crests"
        ).fetchall()
        quarantine_hashes = {x[0] for x in db.execute(
            "SELECT DISTINCT sha256 FROM team_crest_quarantine"
        )} if db.execute(
            "SELECT 1 FROM sqlite_master WHERE name='team_crest_quarantine'"
        ).fetchone() else set()
    with closing(connect(main_path)) as db:
        existing = {x[0]: x[1] for x in db.execute(
            "SELECT team_key,filename FROM team_logos"
        )}
    for team_id,name,filename,sha in entries:
        key = key_fn(name)
        cached = existing.get(key)
        if cached == filename:
            continue
        if cached:
            raise RuntimeError("Conflicting display crest for " + name)
        if sha in quarantine_hashes:
            raise RuntimeError("Quarantined artwork remains active for " + name)
        image_path = Path(logos_dir) / filename
        if (not image_path.is_file()
                or hashlib.sha256(image_path.read_bytes()).hexdigest() != sha):
            raise RuntimeError("Missing or corrupted registry image for " + name)
        with closing(connect(main_path)) as db:
            begin_immediate(db)
            try:
                if db.execute(
                    "SELECT filename FROM team_logos WHERE team_key=?", (key,)
                ).fetchone():
                    raise RuntimeError("Concurrent conflicting saved logo for " + name)
                db.execute(
                    "INSERT INTO team_logos(team_key,team_name,filename,mime_type) VALUES(?,?,?,?)",
                    (key,name,filename,"image/png")
                )
                db.execute("COMMIT")
            except Exception:
                db.rollback()
                raise
        existing[key] = filename
        repaired.append(name)
    return repaired
