"""Offline-first fixture identity resolution prototype (NOT a drop-in match voter).

Identity decisions are separated from discovery. Approximate spelling may help
shortlist a review candidate but NEVER gives an automatic verification vote.
All public functions are pure: no network access, file writes or DB changes.
"""
from __future__ import annotations
from dataclasses import dataclass, asdict
from datetime import date
from difflib import SequenceMatcher
import re
import unicodedata

# Distinct participant categories; do not collapse these into adult first teams.
WOMEN = {'women', 'woman', 'womens', 'ladies', 'female', 'femenino', 'feminino', 'femeni', 'feminin', 'feminines', 'feminine'}
RESERVE = {'reserve', 'reserves', 'reserva', 'reserves', 'castilla', 'ii', 'iii'}
YOUTH = {'youth', 'academy', 'junior', 'juniors', 'under', 'under21'}
PROTECTED = WOMEN | RESERVE | YOUTH
# Note: B, 2 are reserve markers ONLY at the end of the complete team name.
PREFIXES = {'fc', 'fk', 'sk', 'ac', 'sc', 'afk', 'as', 'tsg', 'cd', 'cf', 'ssc', 'sv', 'ss'}
# Do NOT remove the meaningful suffix 'United', 'City', 'Sporting' or arbitrary cities.
TRAILING = {'fc', 'cf', 'sc', 'ac', 'fk', 'sk'}
NEUTRAL = {'club', 'football', 'soccer'}
GENERIC = {'city', 'united', 'sporting', 'athletic', 'olympique', 'town', 'rover', 'rovers', 'rangers', 'real', 'inter'}
TRANSLIT = str.maketrans({'ø':'o', 'ł':'l', 'đ':'d', 'ð':'d', 'þ':'th', 'æ':'ae', 'œ':'oe', 'ß':'ss', 'ı':'i'})

@dataclass(frozen=True)
class NameResult:
    classification: str  # exact, normalized, verified_alias, review, reject
    reason: str
    score: float = 0.0

@dataclass(frozen=True)
class FixtureResult:
    classification: str  # match, review, reject
    reason: str
    home: NameResult
    away: NameResult

def tokens(name: str) -> tuple[str,...]:
    text=str(name or '').casefold().translate(TRANSLIT)
    text=unicodedata.normalize('NFKD', text)
    text=''.join(ch for ch in text if not unicodedata.combining(ch))
    text=re.sub(r'[^a-z0-9]+',' ',text).strip()
    return tuple(text.split())

def normalized(name: str) -> str:
    return ' '.join(tokens(name))

def category(name: str) -> tuple[str, ...]:
    ts=tokens(name)
    seen=[]
    if any(t in WOMEN for t in ts): seen.append('women')
    if any(t in RESERVE for t in ts) or (ts and ts[-1] in {'b', 'ii', 'iii', '2'}): seen.append('reserve')
    if any(t in YOUTH for t in ts) or any(re.fullmatch(r'u\d{1,2}',t) for t in ts):seen.append('youth')
    return tuple(sorted(set(seen)))

def structural(name: str) -> tuple[str, ...]:
    ts=list(tokens(name))
    while len(ts)>1 and ts[0] in PREFIXES: ts.pop(0)
    while len(ts)>1 and ts[-1] in TRAILING: ts.pop()
    return tuple(ts)

def _root(t: str) -> str:
    # Lyonnais -> Lyon, never automatic; only for review shortlist.
    if len(t)>=8 and t.endswith('nais') and len(t[:-4])>=4:
        return t[:-4]
    return t

def compare_name(a: str, b: str, *, verified_aliases=None) -> NameResult:
    """Return match strength; only exact/normalized/verified_alias may be voted.

    verified_aliases is an EXPLICIT reviewer-approved map of alias->canonical.
    No example pairs are pre-approved by this prototype.
    """
    x,y=tokens(a),tokens(b)
    if not x or not y:return NameResult('reject','missing_club_name')
    if category(a)!=category(b):return NameResult('reject','participant_category_mismatch')
    if x==y:return NameResult('exact','identical_normalized_name',1)
    # Existing harmless administrative FC/CF/SC suffix behavior: review only
    # if one side requires the prefix removal in new matching rules.
    xa=structural(a); xb=structural(b)
    if verified_aliases:
        a_id=verified_aliases.get(normalized(a))
        b_id=verified_aliases.get(normalized(b))
        if a_id and a_id==b_id:
            return NameResult('verified_alias','explicitly_approved_canonical_identity',1)
    if xa==xb and xa:
        if len(xa)==1 and len(xa[0])<5:
            return NameResult('reject','short_generic_name')
        # Do not merge two different organizations merely because prefixes drop.
        if x!=xa and y!=xb and (x[0] != y[0]):
            return NameResult('reject','conflicting_club_prefixes')
        return NameResult('review','administrative_prefix_or_suffix_variant',.99)
    # Prevent participant-class leakage even if an abbreviation contains a category label.
    ax=' '.join(x); by=' '.join(y)
    ratio=SequenceMatcher(None,ax,by).ratio()
    significant_a={_root(t) for t in x if len(t)>=4 and t not in GENERIC and t not in PREFIXES}
    significant_b={_root(t) for t in y if len(t)>=4 and t not in GENERIC and t not in PREFIXES}
    overlap=significant_a & significant_b
    if ratio>=.82 and overlap:
        return NameResult('review','high_similarity_with_distinctive_anchor',round(ratio,3))
    return NameResult('reject','insufficient_verified_identity_evidence',round(ratio,3))

def compare_fixture(target:dict, candidate:dict, *, aliases=None) -> FixtureResult:
    h=compare_name(target.get('home'),candidate.get('home'),verified_aliases=aliases)
    a=compare_name(target.get('away'),candidate.get('away'),verified_aliases=aliases)
    if h.classification=='reject' or a.classification=='reject':
        return FixtureResult('reject','home_or_away_identity_unresolved',h,a)
    # A swapped home/away can be a different event, not automatic matching.
    swapped_h=compare_name(target.get('home'), candidate.get('away'),verified_aliases=aliases)
    swapped_a=compare_name(target.get('away'),candidate.get('home'),verified_aliases=aliases)
    if (swapped_h.classification!='reject' and swapped_a.classification!='reject'):
        return FixtureResult('reject','home_away_orientation_ambiguous',h,a)
    d1=target.get('match_date','');d2=candidate.get('match_date','')
    if not d1 or not d2:
        return FixtureResult('reject','date_missing',h,a)
    try:
        d1=date.fromisoformat(str(d1)[:10]);d2=date.fromisoformat(str(d2)[:10])
    except ValueError:
        return FixtureResult('reject','invalid_fixture_date',h,a)
    delta=abs((d1-d2).days)
    if delta>1:return FixtureResult('reject','date_mismatch',h,a)
    for field in ('country','league'):
        v1=normalized(target.get(field));v2=normalized(candidate.get(field))
        if v1 and v2 and v1!=v2:
            # Competition labels need independent alias catalog; do not guess.
            return FixtureResult('reject',field+'_conflict',h,a)
    if delta==1:
        return FixtureResult('review','adjacent_utc_or_local_day_requires_timezone_validation',h,a)
    if h.classification in ('review',) or a.classification in ('review',):
        return FixtureResult('review','club_alias_requires_identity_approval',h,a)
    return FixtureResult('match','same_teams_home_away_and_date',h,a)

def candidate_pool(target:dict, records:list[dict], *, aliases=None) -> list[dict]:
    """Return review candidates or ONE unambiguous exact match; never guess.

    A provider with multiple plausible records for the same fixture is ambiguous.
    """
    outcomes=[]
    for rec in records:
        item=compare_fixture(target,rec,aliases=aliases)
        if item.classification!='reject':
            outcomes.append({'record':rec,'decision':asdict(item)})
    if len(outcomes)>1:
        for row in outcomes:
            row['decision']['classification']='review'
            row['decision']['reason']='multiple_possible_provider_events'
    return outcomes

# Review-only web-text guard: a matching keyword immediately followed by B,
# U21, II or Women is NOT evidence for the corresponding first-team fixture.
WEB_GENERIC = GENERIC | {'football','club','nacional','universidad','reserve','manchester',
                         'sheffield','nottingham','bristol','birmingham','oxford',
                         'cambridge','madrid','saint','stade','town','county','college'}
WEB_BREAKS = {'vs','versus','against','v'}

def _protected_near(terms, start, end, *, fuzzy:bool=False) -> bool:
    if start and terms[start-1] in (PROTECTED | {'b','ii','iii'}):return True
    after=terms[end:end+(5 if fuzzy else 2)]
    for idx,word in enumerate(after):
        if idx>0 and after[idx-1] in WEB_BREAKS:break
        if word in WEB_BREAKS: break
        if word in PROTECTED or word in {'b','ii','iii'} or re.fullmatch(r'u\d{1,2}',word):
            return True
        if word=='u' and idx+1<len(after) and after[idx+1].isdigit():return True
        if not fuzzy:break
    return False

def web_mention_category_safe(team:str, text:str, *, aliases=()) -> bool:
    """Safety filter for an ALREADY matched web mention, never an extra identity vote.

    If a full-team phrase occurs, don't bypass its protected B/U21/Women marker
    by falling back to an isolated long token. Ambiguity fails closed.
    """
    terms=tokens(text)
    if not terms:return False
    patterns=[]
    for name in (team, *aliases):
        t=tokens(name)
        if t and t not in patterns:patterns.append(t)
    bare=structural(team)
    if bare and len(bare)>=2 and bare not in patterns:patterns.append(bare)
    spans=[]
    for pattern in patterns:
        n=len(pattern)
        for i in range(len(terms)-n+1):
            if terms[i:i+n]==pattern:spans.append((i,i+n))
    if spans:return any(not _protected_near(terms,a,b) for a,b in spans)
    distinctive=[t for t in tokens(team)
                 if len(t)>=7 and t not in WEB_GENERIC and t not in PREFIXES]
    if len(distinctive)!=1:return False
    word=distinctive[0]
    return any(not _protected_near(terms,i,i+1,fuzzy=True)
               for i,t in enumerate(terms) if t==word)


# PHASE4_UNIFIED_IDENTITY: the SAME comparator governs fixture adapters and
# individual team images. No guessed alias is promoted to an automatic vote.
def source_fixture(target: dict, home: str, away: str, source_date: str,
                   *, country: str = '', league: str = '', aliases=None) -> FixtureResult:
    """Classify a provider's actual home/away/date before reading its values.

    Do not inject source-country as a target identity. The target's country and
    league are the original known identity, never facts learnt from this source.
    """
    known_country = str(target.get('country') or '').strip()
    known_league = str(target.get('league') or '').strip()
    if ',' in known_league:
        prefix, tail = (v.strip() for v in known_league.split(',', 1))
        if not known_country or normalized(prefix) == normalized(known_country):
            known_country = known_country or prefix
            known_league = tail
    # These small competition labels are already explicitly mapped by the
    # installed ESPN adapter. Keep the country check; don't equate two leagues
    # merely because they share a name across different countries.
    league_labels = {'japanese j1 league':'j1 league',
                     'j league division 1':'j1 league',
                     'japanese j2 league':'j2 league',
                     'english premier league':'premier league',
                     'epl':'premier league',
                     'german bundesliga':'bundesliga',
                     'french ligue 1':'ligue 1',
                     'spanish la liga':'la liga'}
    country_labels = {'czech republic':'czechia',
                      'united states of america':'united states',
                      'usa':'united states'}
    # Country-scoped equivalence confirmed by the 2026/27 Czech league
    # authority and TheSportsDB's exact second-division fixture ID.
    # Do NOT conflate with the separate Czech first-division Chance Liga.
    if (normalized(known_country) in ('czechia','czech republic') and
            normalized(country) in ('czechia','czech republic')):
        league_labels['chance narodni liga']='czech national football league'
    # ANFP's 2026 Liga de Primera is the same Chilean FIRST division
    # listed by TheSportsDB as Chile Primera Division. Never map Primera B.
    if normalized(known_country)=='chile' and normalized(country)=='chile':
        league_labels['liga de primera']='chile primera division'
    def canonical(value, catalog):
        text = normalized(value)
        return catalog.get(text,text)
    selected = {'home':target.get('home'),'away':target.get('away'),
                'match_date':target.get('match_date'),
                'country':canonical(known_country,country_labels),
                'league':canonical(known_league,league_labels)}
    proposed = {'home':home,'away':away,'match_date':source_date,
                'country':canonical(country,country_labels),
                'league':canonical(league,league_labels)}
    return compare_fixture(selected,proposed,aliases=aliases)


def crest_identity(target_team: str, candidate_team: str) -> NameResult:
    """Club-image identity: reject different category; fuzzy is review only."""
    return compare_name(target_team,candidate_team)


# Retrieval aliases are DISCOVERY QUERIES ONLY. These two spellings already
# exist as review-only search variants in the installed Czech V3 Tavily engine;
# they do not establish team equivalence or authorize automatic verification.
DISCOVERY_ALIASES = {
    'osc lille':'LOSC Lille',
    'losc lille':'OSC Lille',
    'olympique lyon':'Olympique Lyonnais',
    'olympique lyonnais':'Olympique Lyon',
}

def discovery_variant(team: str) -> str:
    """One bounded alternate query, never an identity assertion."""
    name=str(team or '').strip()
    known=DISCOVERY_ALIASES.get(normalized(name))
    if known:return known
    raw=tokens(name)
    bare=structural(name)
    if len(raw)>len(bare) and len(bare)>=2 and len(' '.join(bare))>=10:
        return ' '.join(bare)
    return name

def discovery_queries(home: str, away: str):
    """At most two pairs; no unbounded fuzzy query expansion."""
    original=(str(home or '').strip(),str(away or '').strip())
    alternate=(discovery_variant(original[0]),discovery_variant(original[1]))
    return (original,) if alternate==original else (original,alternate)
