"""Curated official fixture evidence for HUMAN review only.

No network, credential, vote, identity-registry or application database writes.
An entry is eligible only for the exact pending SoccerRating queue fixture.
Original AFC team names are displayed as provenance, NOT global approved aliases.
"""
from __future__ import annotations

from datetime import datetime
from pathlib import Path
from urllib.parse import urlsplit
import json
import re
import sqlite3
import hashlib
import io

CATALOG = Path(__file__).with_name("sr_official_manual_fixtures.json")
QUEUE_DB = Path(__file__).with_name("soccerrating_queue.db")
SOURCE = "AFC official match schedule (manual)"
_FIELDS = ("kickoff", "league", "country")


def _catalog():
    """Fail closed for missing, stale, malformed, or altered catalog entries."""
    try:
        if CATALOG.stat().st_size > 64_000:
            return {}
        data = json.loads(CATALOG.read_text(encoding="utf-8"))
        if data.get("schemaVersion") != 1 or not isinstance(data.get("records"), list):
            return {}
    except (OSError, ValueError, TypeError):
        return {}
    verified = {}
    for r in data["records"][:64]:
        if not isinstance(r, dict):
            continue
        try:
            fid = str(r["queueId"])
            home, away = (str(r[k]).strip() for k in ("queueHome", "queueAway"))
            original_home, original_away = (str(r[k]).strip()
                                             for k in ("officialHome", "officialAway"))
            date = str(r["matchDate"])
            utc = str(r["kickoffUTC"])
            competition = str(r["competition"]).strip()
            region = str(r.get("competitionRegion", "")).strip()
            if region not in ("", "Asia", "Portugal", "Poland", "Italy") or (region == "Asia" and r.get("regionType") != "continental") or (region in ("Portugal","Poland","Italy") and r.get("regionType") != "national"):
                continue
            url = str(r["sourceUrl"])
            parsed = urlsplit(url)
            afc = (parsed.hostname == "assets.the-afc.com" and
                   parsed.path.lower().endswith(".pdf") and
                   parsed.path.startswith("/2026-27_ACL_Elite/Downloads/Match_Schedule/") and region in ("", "Asia"))
            portugal = (parsed.hostname in ("www.ligaportugal.pt", "ligaportugal.pt") and
                        re.fullmatch(r"/match/[0-9]{8}/ligaportugalbetclic/[0-9]+/[0-9]+", parsed.path) and
                        region == "Portugal" and r.get("regionType") == "national" and
                        competition == "Primeira Liga")
            poland = (parsed.hostname in ("www.chrobry-glogow.pl","chrobry-glogow.pl") and
                      re.fullmatch(r"/Klub/Aktualnosci/[A-Za-z0-9-]+~n[0-9]+", parsed.path) and
                      region == "Poland" and r.get("regionType") == "national" and competition == "I Liga")
            italy = (parsed.hostname in ("www.barletta1922.com","barletta1922.com") and
                     parsed.path=="/press/biglietteria-interu23" and
                     region=="Italy" and r.get("regionType")=="national" and
                     competition=="Serie C - Group C" and
                     (fid,home,away,date,original_home,original_away,utc)==
                     ("sr_a5b7990b3970948b86aab0e8","Barletta Calcio","Inter Milan II","2026-11-29","Barletta","Inter U23","2026-11-29 11:30"))
            if (not re.fullmatch(r"sr_[a-f0-9]{24}", fid)
                or not all((home, away, original_home, original_away, competition))
                or max(map(len, (home, away, original_home, original_away, competition))) > 120
                or parsed.scheme != "https" or not (afc or portugal or poland or italy) or parsed.port not in (None,443)
                or parsed.username or parsed.password or parsed.query or parsed.fragment
                or not re.fullmatch(r"\d{4}-\d{2}-\d{2}", date)
                or datetime.strptime(utc, "%Y-%m-%d %H:%M").date()
                    != datetime.strptime(date, "%Y-%m-%d").date()):
                continue
            # Duplicate record IDs are never trusted as independent evidence.
            if fid in verified:
                verified.pop(fid, None)
                continue
            verified[fid] = r
        except (KeyError, ValueError, TypeError, OverflowError):
            continue
    return verified


def _queue_row(fid: str):
    """Read-only and only when a catalog ID exists. Never run queue setup."""
    if not QUEUE_DB.is_file():
        return None
    try:
        conn = sqlite3.connect("file:" + QUEUE_DB.as_posix() + "?mode=ro",
                               uri=True, timeout=2)
        try:
            conn.execute("PRAGMA query_only=ON")
            row = conn.execute(
                "SELECT id, home, away, match_date, status, country, league FROM candidates WHERE id=?",
                (fid,)
            ).fetchone()
        finally:
            conn.close()
        if not row:
            return None
        return dict(zip(("id", "home", "away", "match_date", "status", "country", "league"), row))
    except sqlite3.Error:
        return None


def record_for(fixture):
    """Require exact queue id, home, away, date and still-pending status."""
    if isinstance(fixture, str):
        row = _queue_row(fixture)
    elif isinstance(fixture, dict):
        row = fixture
    else:
        return None
    if not row:
        return None
    record = _catalog().get(str(row.get("id", "")))
    if not record:
        return None
    expected = (record["queueId"], record["queueHome"],
                record["queueAway"], record["matchDate"])
    actual = tuple(str(row.get(k, "")) for k in ("id", "home", "away", "match_date"))
    if actual != expected or str(row.get("status")) != "pending":
        return None
    return record


def reserve_review_route(fixture):
    """Exact reviewed fixture-only route; never a global alias or provider vote."""
    rec=record_for(fixture)
    if not rec or rec.get("reserveReviewRoute") is not True or rec.get("competitionRegion")!="Italy":
        return {}
    row=_queue_row(fixture) if isinstance(fixture,str) else fixture
    if row.get("country") and str(row["country"]).strip().casefold()!="italy":
        return {}
    if row.get("league") and "serie c" not in str(row["league"]).casefold():
        return {}
    return {"country":"Italy","home":rec["officialHome"],"away":rec["officialAway"],"reviewOnly":True,"reserveReview":True}

def _source_name(rec):
    if rec.get("competitionRegion")=="Italy":
        return "Official Italian club fixture (manual)"
    if rec.get("competitionRegion")=="Poland":
        return "Official Polish club fixture (manual)"
    return "Liga Portugal official fixture (manual)" if rec.get("regionType")=="national" else SOURCE


def suggestions_for(fixture):
    """Return official-source choices for explicit human approval, never votes.

    AFC is a continental body, so Asia is a COMPETITION REGION, not a nationality.
    """
    rec = record_for(fixture)
    if not rec:
        return {}
    evidence = {
        "source": _source_name(rec),
        "reference": str(rec["sourceUrl"]),
        "recovery": True,
        "officialSchedule": True,
        "identityReview": True,
        "identityReason": "Official club names differ; confirm this exact fixture",
        "sourceHome": str(rec["officialHome"]),
        "sourceAway": str(rec["officialAway"]),
        "sourceEventId": str(rec.get("sourceEventCode", "")),
        "sourceDocument": str(rec.get("sourceDocument", "")),
        "sourceAsOf": str(rec.get("sourceAsOf", "")),
    }
    choices = {
        "kickoff": [{**evidence, "value": str(rec["kickoffUTC"])}],
        "league": [{**evidence, "value": str(rec["competition"])}],
    }
    if rec.get("competitionRegion") == "Asia" and rec.get("regionType") == "continental":
        choices["country"] = [{**evidence, "value": "Asia",
            "regionalScope": "continental",
            "identityReason": "AFC is the Asian Football Confederation; region is not a national association",
            "countryNotNation": True}]
    if rec.get("competitionRegion") in ("Portugal","Poland","Italy") and rec.get("regionType")=="national":
        choices["country"]=[{**evidence,"value":rec["competitionRegion"],"identityReason":"Official domestic competition schedule; confirm this exact fixture"}]
    return choices


def enrich(fields: dict, fixture):
    """Only append source-backed manual choices; preserve states, votes, decisions."""
    rec = record_for(fixture)
    if not rec or not isinstance(fields, dict):
        return False
    for field, choices in suggestions_for(fixture).items():
        entry = fields.get(field)
        if not isinstance(entry, dict):
            # Do not invent a voting field if the main verifier has not run.
            continue
        evidence = entry.get("evidence")
        if not isinstance(evidence, list):
            continue
        known = {(str(x.get("source")), str(x.get("value")), str(x.get("reference")))
                 for x in evidence if isinstance(x, dict)}
        for item in choices:
            key = (item["source"], item["value"], item["reference"])
            if key not in known:
                evidence.append(item)
                known.add(key)
        note = ("Official Italian club fixture: manual review available; no automatic vote" if rec.get("competitionRegion")=="Italy" else "Official Polish club fixture: manual review available; no automatic vote" if rec.get("competitionRegion")=="Poland" else "Official Liga Portugal fixture: manual review available; no automatic vote" if rec.get("regionType")=="national" else "Official AFC schedule: manual review available; no automatic vote")
        if note not in str(entry.get("message", "")):
            entry["message"] = (str(entry.get("message") or "").strip()
                                + (" · " if entry.get("message") else "") + note)
    fields["officialReview"] = {
        "source": _source_name(rec), "reference": str(rec["sourceUrl"]),
        "scope": "exact_fixture_only", "voting": False,
        "countryNeedsSeparateDecision": True,
        "competitionRegion": str(rec.get("competitionRegion", "")),
        "regionType": str(rec.get("regionType", "")),
        "notes": ("Domestic competition country requires explicit review." if rec.get("regionType")=="national" else "AFC competition spans countries. Use Asia as a manually approved region, not either team nationality."),
        "sourceAsOf": str(rec.get("sourceAsOf", "")),
        "localKickoff": str(rec.get("localKickoff", "")),
        "venue": str(rec.get("venue", "")),
    }
    return True


def domestic_country_proof(fixture, fields, decisions, *, today=None):
    """Derive a domestic competition country from separately audited evidence.
    Not a provider vote, manual approval, team-nationality inference or web guess.
    All existing catalog suggestions stay review-only without explicit proof.
    Re-evaluate against current selections on every read/import; never persist
    a derived country that could survive a changed league or kickoff selection.
    """
    try:
        from datetime import date, timezone
        row=_queue_row(fixture) if isinstance(fixture,str) else fixture
        rec=record_for(row)
        if not rec or rec.get('regionType')!='national':return None
        p=rec.get('domesticCountryProof')
        if not isinstance(p,dict):return None
        expected=(rec['competitionRegion'],rec['competition'],rec['matchDate'],rec['kickoffUTC'],rec['queueHome'],rec['queueAway'],rec['sourceUrl'])
        if tuple(p.get(k) for k in ('country','competition','matchDate','kickoffUTC','home','away','leagueAuthority'))!=expected:return None
        # Only currently audited domestic authority routes are supported.
        if (p['country'],p['competition'])!=('Portugal','Primeira Liga'):return None
        day=date.fromisoformat(p['reviewedAsOf'])
        now=today or datetime.now(timezone.utc).date()
        if day>now or (now-day).days>7:return None
        refs=p.get('clubCorroboration')
        if not isinstance(refs,list) or len(refs)!=2:return None
        hosts=set()
        for u in refs:
            q=urlsplit(u)
            if q.scheme!='https' or q.username or q.password or q.port not in (None,443) or q.query or q.fragment:return None
            if q.hostname=='www.cdnacional.pt' and q.path.startswith('/eventos/'):hosts.add('nacional')
            elif q.hostname=='csmaritimo.pt' and q.path.startswith('/noticias/'):hosts.add('maritimo')
            else:return None
        if hosts!={'nacional','maritimo'}:return None
        if set(refs)-set(rec.get('corroboration') or []):return None
        def confirmed(k):
            m=(decisions or {}).get(k) or {}
            a=fields.get(k) or {}
            return m.get('value') if m.get('state')=='manual' else a.get('value') if a.get('state')=='verified' else None
        if confirmed('league')!=p['competition'] or confirmed('kickoff')!=p['kickoffUTC']:return None
        if confirmed('country') or (decisions or {}).get('country'):return None
        if row.get('country') and row['country'].strip().casefold()!=p['country'].casefold():return None
        if row.get('league') and row['league'].strip().casefold()!=p['competition'].casefold():return None
        c=fields.get('country') or {}
        if c.get('state')!='review' or c.get('value') or c.get('dissent'):return None
        if any(str(x.get('value') or '').strip().casefold()!=p['country'].casefold()
               for x in c.get('evidence',[]) if x.get('value')):return None
        # Existing contrary fixture evidence is a reason to abstain.
        for k in ('league','kickoff'):
            if (fields.get(k) or {}).get('dissent'):return None
        return {'country':p['country'],'competition':p['competition'],'kickoffUTC':p['kickoffUTC'],
                'reference':p['leagueAuthority'],'corroboration':refs,'reviewedAsOf':p['reviewedAsOf'],
                'basis':'audited_domestic_competition','voting':False}
    except (AttributeError,KeyError,TypeError,ValueError,OverflowError):
        return None


def approved_choice(fixture, field: str, value: str) -> bool:
    """Backend explicit human approval still required; never approve automatically."""
    return field in _FIELDS and any(
        str(item["value"]) == str(value)
        for item in suggestions_for(fixture).get(field, ())
    )


# FA_AFC_ASIA_REGIONAL_MARKER_V1 — Not a national flag or an AFC trademark.
def badge_country(value):
    """Safely extract the matching country/region from existing image labels."""
    text = str(value or "").strip()
    if text == "Asia regional badge":
        return "Asia"
    return text.removesuffix(" national flag")


def asia_badge_candidates(region, directory):
    """Provide one ORIGINAL neutral region badge for explicit reviewer approval.

    No network request, no fabricated national flag and no provider vote.
    Image is stored only as a local candidate, never in the global logo
    library until the user explicitly approves the specific candidate.
    """
    if region != "Asia":
        return [], "Not a supported continental region."
    from PIL import Image, ImageDraw, ImageFont
    image = Image.new("RGBA", (160, 160), (0, 0, 0, 0))
    draw = ImageDraw.Draw(image)
    draw.rounded_rectangle((5, 5, 155, 155), radius=35,
                           fill=(18, 58, 96, 255), outline=(89, 189, 208, 255),
                           width=3)
    draw.ellipse((41, 22, 119, 100), outline=(216, 242, 243, 255), width=4)
    draw.arc((58, 22, 102, 100), 90, 270, fill=(216, 242, 243, 255), width=3)
    draw.arc((58, 22, 102, 100), 270, 90, fill=(216, 242, 243, 255), width=3)
    draw.line((42, 60, 118, 60), fill=(216, 242, 243, 255), width=3)
    draw.arc((45, 39, 115, 82), 5, 175, fill=(216, 242, 243, 255), width=2)
    draw.arc((45, 39, 115, 82), 185, 355, fill=(216, 242, 243, 255), width=2)
    try:
        font = ImageFont.truetype(r"C:\Windows\Fonts\segoeuib.ttf", 22)
    except (OSError, ValueError):
        font = ImageFont.load_default()
    draw.text((80, 125), "ASIA", anchor="mm", font=font,
              fill=(255, 255, 255, 255), stroke_width=0)
    out = io.BytesIO()
    image.save(out, format="PNG", optimize=True)
    content = out.getvalue()
    digest = hashlib.sha256(content).hexdigest()
    directory = Path(directory)
    directory.mkdir(parents=True, exist_ok=True)
    target = directory / (digest + ".png")
    if not target.exists():
        target.write_bytes(content)
    return [{
        "source": "Original neutral regional badge (manual)",
        "value": "Asia regional badge",
        "id": digest,
        "image": "/fixture-flag-image/" + digest + ".png",
        "reference": "locally-generated-neutral-marker",
        "regionalBadge": True,
        "license": "Original generic artwork; not an AFC emblem or a national flag",
    }], "Asia is a continental region, not a nation. Approve this neutral regional badge manually."
