"""Multi-source read-only fixture enrichment for pending SoccerRating review entries.

Four providers are consulted where available; three INDEPENDENT matching votes
are required for automatic verification. Two votes do not count. All review decisions live in a separate
SQLite database. Nothing in this module imports or edits a football match.
"""
from __future__ import annotations

import base64
import hashlib
import datetime as dt
import json
import os
import re
import sqlite3
import threading
import time
from collections import defaultdict
from contextlib import closing
from pathlib import Path
from urllib.parse import urlencode

import sr_logo_discovery as art
import sr_fixture_identity as identity  # PHASE4_UNIFIED_IDENTITY
import team_identity_registry as team_registry  # GLOBAL_TEAM_IDENTITY_V1
import sr_unified_evidence_contract as unified  # PHASE4_UNIFIED_SOURCES
import sr_expanded_source_recovery as added_sources  # FA_UNIFIED_16_SOURCES_REVIEW
import sr_four_free_recovery as free_recovery  # FA_FOUR_FREE_RECOVERY_V1
import sr_missing_info_recovery as web_recovery  # FA_AUTOMATIC_MISSING_INFORMATION_V1
import sr_source_policy as source_policy  # FA_SR_SOURCE_CLEANUP_8_OF_16_20261122
import sr_official_manual_evidence as official_review  # FA_AFC_OFFICIAL_MANUAL_EVIDENCE_20261122

DB = Path(__file__).resolve().parent / 'soccerrating_fixture_verification.db'
LOCK = threading.RLock()
WORKER = threading.Lock()
FLAG_WORKER = threading.Lock()  # Phase12D: country-flag-only lookup, no fixture quota
PROGRESS = {'checked': 0, 'total': 0, 'current': '', 'finishedAt': ''}
FLAGS = Path(__file__).resolve().parent / 'fixture_flag_candidates'
MAX_PER_SCAN = 120
_ESPN_CACHE = {}
RETRY = 6 * 3600
SOURCES = ('API-Football', 'TheSportsDB', 'ESPN', 'football-data.org')

# Conservative mappings for ESPN's independently published league fixtures.
# An unsupported competition remains unverified; never guess its country.
ESPN_LEAGUES = {
    'Japan': ('jpn.1', 'jpn.2'), 'England': ('eng.1', 'eng.2', 'eng.3', 'eng.4'),
    'Spain': ('esp.1', 'esp.2'), 'Italy': ('ita.1', 'ita.2'),
    'Germany': ('ger.1', 'ger.2'), 'France': ('fra.1', 'fra.2'),
    'Portugal': ('por.1',), 'Netherlands': ('ned.1',),
    'Scotland': ('sco.1',), 'United States': ('usa.1',),
    'Brazil': ('bra.1',), 'Argentina': ('arg.1',),
    # 2026 public ESPN scoreboard returned exact dated event/team IDs for each.
    'Chile': ('chi.1',), 'Sweden': ('swe.1',),
}
KNOWN_LEAGUES = {
    'jpn.1': ('Japan', 'J1 League'), 'jpn.2': ('Japan', 'J2 League'),
    'eng.1': ('England', 'Premier League'), 'eng.2': ('England', 'Championship'),
    'eng.3': ('England', 'League One'), 'eng.4': ('England', 'League Two'),
    'esp.1': ('Spain', 'La Liga'), 'esp.2': ('Spain', 'Segunda Division'),
    'ita.1': ('Italy', 'Serie A'), 'ita.2': ('Italy', 'Serie B'),
    'ger.1': ('Germany', 'Bundesliga'), 'ger.2': ('Germany', '2. Bundesliga'),
    'fra.1': ('France', 'Ligue 1'), 'fra.2': ('France', 'Ligue 2'),
    'por.1': ('Portugal', 'Primeira Liga'), 'ned.1': ('Netherlands', 'Eredivisie'),
    'sco.1': ('Scotland', 'Scottish Premiership'),
    'usa.1': ('United States', 'MLS'), 'bra.1': ('Brazil', 'Serie A'),
    'arg.1': ('Argentina', 'Primera Division'),
    'chi.1': ('Chile', 'Chile Primera Division'),
    'swe.1': ('Sweden', 'Swedish Allsvenskan'),
}
LEAGUE_ALIASES = {
    'japanese j1 league':'j1 league', 'j league division 1':'j1 league',
    'j1 league':'j1 league', 'japanese j2 league':'j2 league',
    'english premier league':'premier league', 'epl':'premier league',
    'spanish la liga':'la liga', 'italian serie a':'serie a',
    'german bundesliga':'bundesliga', 'french ligue 1':'ligue 1',
    'major league soccer':'mls', 'usa major league soccer':'mls',
}


def clean(s):
    return re.sub(r'\s+', ' ', str(s or '').strip())[:160]


def league_key(value):
    val = art.ident(value)
    return LEAGUE_ALIASES.get(val, val)


def _league_vote_key(value, country):
    key=league_key(value)
    if art.ident(country)=='poland' and key in ('i liga','polish i liga','betclic 1 liga','betclic i liga','1 liga','polish first league'):
        return ('Poland','I Liga')
    return ('',key)


def source_key(source):
    return clean(source)


def setup():
    FLAGS.mkdir(exist_ok=True)
    with LOCK, closing(sqlite3.connect(DB)) as c:
        c.execute('''CREATE TABLE IF NOT EXISTS fixture_checks (
            id TEXT PRIMARY KEY, checked_at INTEGER NOT NULL,
            values_json TEXT NOT NULL DEFAULT '{}',
            evidence_json TEXT NOT NULL DEFAULT '{}',
            decisions_json TEXT NOT NULL DEFAULT '{}',
            errors_json TEXT NOT NULL DEFAULT '{}')''')
        c.commit()


def get_conn():
    c = sqlite3.connect(DB, timeout=10)
    c.row_factory = sqlite3.Row
    return c


def when_utc(text):
    if not text: return ''
    try:
        v = dt.datetime.fromisoformat(str(text).replace('Z', '+00:00'))
        if v.tzinfo is None: return ''  # Never infer provider timezone.
        return v.astimezone(dt.timezone.utc).strftime('%Y-%m-%d %H:%M')
    except (TypeError, ValueError): return ''


def _sportsdb_documented_utc(event):
    """Return one UTC minute only when the provider's UTC fields corroborate.

    TheSportsDB staff document dateEvent, strTime and strTimestamp as UTC
    even though strTimestamp typically lacks a Z suffix. The fields can be
    imported from user/community schedules and occasionally disagree.
    Never fill UTC from an uncorroborated single value or a midnight default.
    This is ONE provider observation, not two independent source votes.
    """
    if not isinstance(event,dict):
        return ''
    day=str(event.get('dateEvent') or '').strip()
    timestamp=str(event.get('strTimestamp') or '').strip()
    clock=str(event.get('strTime') or '').strip().removesuffix('Z')
    if (not re.fullmatch(r'\d{4}-\d{2}-\d{2}',day)
        or (clock and not re.fullmatch(r'\d{2}:\d{2}(?::\d{2})?',clock))
        or not re.fullmatch(
            r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2})?'
            r'(?:Z|[+-]\d{2}:\d{2})?',timestamp)):
        return ''
    try:
        parsed=dt.datetime.fromisoformat(timestamp.replace('Z','+00:00'))
        # A timezone-qualified timestamp is already explicit UTC evidence.
        # Preserve that existing behavior when strTime is unavailable.
        # Unzoned timestamps still require a corroborating strTime field.
        if not clock:
            if parsed.tzinfo is None:return ''
            utc=parsed.astimezone(dt.timezone.utc)
            if (utc.date().isoformat()!=day or
                (utc.hour,utc.minute)==(0,0)):
                return ''
            return utc.strftime('%Y-%m-%d %H:%M')
        from_time=dt.time.fromisoformat(clock)
        if from_time.hour==0 and from_time.minute==0:
            return ''  # Source regularly uses midnight for unknown times.
        # For timezone-free strTimestamp only, apply the provider's documented
        # UTC convention after requiring its independent strTime field agree.
        if parsed.tzinfo is None:
            parsed=parsed.replace(tzinfo=dt.timezone.utc)
        utc=parsed.astimezone(dt.timezone.utc)
        if (utc.date().isoformat()!=day or
            (utc.hour,utc.minute)!=(from_time.hour,from_time.minute)):
            return ''
        return utc.strftime('%Y-%m-%d %H:%M')
    except (ValueError,TypeError,OverflowError):
        return ''


def _provider_event(fixture, home, away, event_date, *, country='', league='',
                    provider_team_ids=None, provider_id_source='api_football'):
    # Explicit source IDs only strengthen this fixture's identity evidence.
    # Unverified registry aliases cannot vote without a compatible provider ID.
    if provider_team_ids is not None:
        aliases, conflict = team_registry.provider_event_alias_map(
            fixture.get('home'), fixture.get('away'), home, away,
            provider=provider_id_source,home_id=provider_team_ids[0],
            away_id=provider_team_ids[1],
            # Only an independently known SoccerRating country may license an
            # alias bridge; never bootstrap it from this same provider event.
            country=fixture.get('country') or '')
        if conflict:
            return identity.FixtureResult(
                'reject','provider_team_id_conflict',
                identity.NameResult('reject','provider_team_id_conflict'),
                identity.NameResult('reject','provider_team_id_conflict'))
    else:
        aliases = team_registry.alias_map_for_fixture(
            fixture.get('home'), fixture.get('away'), home, away,
            country=fixture.get('country') or '')
    return identity.source_fixture(fixture, home, away, event_date,
                                   country=country, league=league, aliases=aliases)


def event_match(home, away, event_home, event_away):
    # Legacy helper retained for callers; no fuzzy match is an automatic vote.
    h=identity.compare_name(home,event_home)
    a=identity.compare_name(away,event_away)
    return all(x.classification in ('exact','normalized','verified_alias') for x in (h,a))


def _event_record(fixture, home, away, event_date, record, event_id,
                  *, home_team_id=None, away_team_id=None):
    provider_name={'API-Football':'api_football','ESPN':'espn',
                   'football-data.org':'football_data_org',
                   'TheSportsDB':'thesportsdb'}.get(record.get('source'))
    ids=(home_team_id,away_team_id) if provider_name and (
        home_team_id is not None or away_team_id is not None) else None
    result=_provider_event(fixture,home,away,event_date,
                           country=record.get('country',''),league=record.get('league',''),
                           provider_team_ids=ids,
                           provider_id_source=provider_name or 'api_football')
    if result.classification=='reject':return None
    return {**record, '_identity':result.classification,
            '_identityReason':result.reason,
            '_identityHome':str(home or '')[:100], '_identityAway':str(away or '')[:100],
            '_eventId':str(event_id or '')[:100],
            '_eventDate':str(event_date or '')[:10],
            '_providerTeamIds':(str(home_team_id or ''),str(away_team_id or ''))}


def api_football(fixture, _country=''):
    """One shared cached request per UTC fixture date, guarded by free quota."""
    if not art.api_football_key():return None
    dates=(fixture['match_date'],)
    matches=[]
    for date in dates:
        payload=art.api_football_request('fixtures',{'date':date,'timezone':'UTC'},ttl=3600)
        for row in (payload.get('response') or []):
            if not isinstance(row,dict):continue
            teams=row.get('teams') or {}
            h=(teams.get('home') or {}).get('name') or ''
            a=(teams.get('away') or {}).get('name') or ''
            fixture_info=row.get('fixture') or {}
            status=(fixture_info.get('status') or {}).get('short','')
            league=row.get('league') or {}
            # TBD fixtures have no dependable start time; other fields can vote.
            when='' if status=='TBD' else when_utc(fixture_info.get('date'))
            entry=_event_record(fixture,h,a,fixture_info.get('date','')[:10],
                {'source':'API-Football','kickoff':when,
                 'country':clean(league.get('country')),
                 'league':clean(league.get('name')),
                 'reference':'https://www.api-football.com/'},fixture_info.get('id'),
                 home_team_id=(teams.get('home') or {}).get('id'),
                 away_team_id=(teams.get('away') or {}).get('id'))
            if entry:matches.append(entry)
    return unique_fixture(matches)

def _sportsdb_unique_known_team_pair(fixture):
    """Discover source team IDs only from existing one-to-one same-country Reep claims.

    Proposed aliases may direct a lookup, but cannot produce a vote. A single
    alternate women/youth/reserve claim makes discovery ambiguous, even if
    that rival record has no source-ID mapping. Unknown country also abstains.
    """
    country=team_registry._country(fixture.get('country'))
    if not country or not team_registry.DB.is_file():
        return None
    ids=[]
    try:
        db='file:'+str(team_registry.DB.resolve())+'?mode=ro'
        with closing(sqlite3.connect(db,uri=True,timeout=10)) as c:
            c.row_factory=sqlite3.Row
            for name in (fixture.get('home'),fixture.get('away')):
                if team_registry._class(name):
                    return None
                claims=c.execute("""SELECT DISTINCT t.team_id,t.canonical_name,t.category,
                          t.gender,p.external_id FROM aliases a
                     JOIN teams t ON t.team_id=a.team_id
                     LEFT JOIN provider_ids p ON p.team_id=t.team_id
                        AND p.provider='thesportsdb' AND p.namespace='team'
                    WHERE t.source='Reep' AND t.country_key=? AND a.name_key=?""",
                    (country,team_registry.norm(name))).fetchall()
                if len({r['team_id'] for r in claims})!=1:
                    return None
                if any(r['gender']!='men' or r['category'] or
                       team_registry._class(r['canonical_name'],r['category'],r['gender'])
                       for r in claims):
                    return None
                external={str(r['external_id']) for r in claims if r['external_id']}
                if len(external)!=1:
                    return None
                ids.append(next(iter(external)))
    except (sqlite3.Error,OSError,ValueError,TypeError):
        return None
    return tuple(ids) if len(ids)==2 and ids[0]!=ids[1] else None


def _sportsdb_dated_id_event(fixture):
    """At most two source-ID-constrained queries; never guess club identity or UTC."""
    pair=_sportsdb_unique_known_team_pair(fixture)
    if not pair:return []
    try:
        wanted=dt.date.fromisoformat(fixture['match_date'])
    except (ValueError,TypeError,KeyError):
        return []
    # Original names already failed. An exact Reep canonical-label query is
    # permitted ONLY when both original names uniquely resolved to Reep senior
    # teams bearing these source provider IDs in the independently known country.
    names=[]
    country_key=team_registry._country(fixture.get('country'))
    try:
        uri='file:'+str(team_registry.DB.resolve())+'?mode=ro'
        with closing(sqlite3.connect(uri,uri=True,timeout=10)) as c:
            for identifier in pair:
                rows=c.execute("""SELECT DISTINCT t.canonical_name FROM provider_ids p
                     JOIN teams t ON t.team_id=p.team_id
                     WHERE p.provider='thesportsdb' AND p.namespace='team'
                       AND p.external_id=? AND t.source='Reep'
                       AND t.country_key=? AND t.gender='men' AND t.category=''""",
                       (identifier,country_key)).fetchall()
                if len(rows)!=1:return []
                names.append(rows[0][0])
    except (sqlite3.Error,OSError,ValueError,TypeError):
        return []
    original_names=(team_registry.norm(fixture.get('home')),
                    team_registry.norm(fixture.get('away')))
    canonical_names=tuple(map(team_registry.norm,names))
    canonical_url=('https://www.thesportsdb.com/api/v1/json/123/searchevents.php?'
           +urlencode({'e':names[0]+'_vs_'+names[1],'d':fixture['match_date']}))
    today=dt.datetime.now(dt.timezone.utc).date()
    nearby='eventsnext.php' if wanted>=today else 'eventslast.php'
    recent_url=('https://www.thesportsdb.com/api/v1/json/123/'+nearby+'?'
                +urlencode({'id':pair[0]}))
    queries=([recent_url,canonical_url] if wanted>today else
             [canonical_url,recent_url])
    # Don't repeat the already attempted original-name search if the
    # canonical labels are identical; no fuzzy fan-out or third-party source.
    if canonical_names==original_names:
        queries=[url for url in queries if url!=canonical_url]
    for url in queries[:2]:
        try:
            response=art.get_json(url)
        except (OSError,ValueError,TypeError):
            continue
        if not isinstance(response,dict):continue
        events=(response.get('events') or response.get('event')
                or response.get('results') or [])
        results=[]
        for event in events[:12]:
            if not isinstance(event,dict):continue
            if (str(event.get('idHomeTeam'))!=pair[0] or
                str(event.get('idAwayTeam'))!=pair[1] or
                event.get('dateEvent')!=fixture['match_date']):
                continue
            if event.get('strSport') and str(event['strSport']).casefold()!='soccer':
                continue
            kickoff=_sportsdb_documented_utc(event)
            record=_event_record(fixture,event.get('strHomeTeam'),event.get('strAwayTeam'),
                event.get('dateEvent'),
                {'source':'TheSportsDB','kickoff':kickoff,
                 'country':clean(event.get('strCountry')),
                 'league':clean(event.get('strLeague')),
                 'reference':'https://www.thesportsdb.com/event/'+str(event.get('idEvent') or '')},
                event.get('idEvent'),
                home_team_id=event.get('idHomeTeam'),away_team_id=event.get('idAwayTeam'))
            if record:results.append(record)
        if results:return results
    return []


def sportsdb(fixture, _country=''):
    """Try the original names first; at most ONE safe alternate lookup.

    Alternate labels only retrieve candidates. Every returned event must pass
    the same full fixture identity resolver and remains review-only when its
    names are not already verified. No guessed aliases count as votes.
    """
    found=[]
    for home_query,away_query in team_registry.discovery_queries(
        fixture['home'], fixture['away'], source='TheSportsDB',
        country=fixture.get('country','')):
        name=home_query+'_vs_'+away_query
        url='https://www.thesportsdb.com/api/v1/json/123/searchevents.php?'+urlencode({
            'e':name,'d':fixture['match_date']})
        data=art.get_json(url)
        for e in (data.get('event') or [])[:12]:
            if not isinstance(e,dict):continue
            # TheSportsDB also covers hockey and other sports with same names.
            # The event must be a soccer fixture before it can be considered.
            if e.get('strSport') and str(e.get('strSport')).casefold()!='soccer':
                continue
            start=_sportsdb_documented_utc(e)
            entry=_event_record(fixture,e.get('strHomeTeam'),e.get('strAwayTeam'),
                 e.get('dateEvent'),{'source':'TheSportsDB','kickoff':start,
                  'country':clean(e.get('strCountry')),'league':clean(e.get('strLeague')),
                  'reference':'https://www.thesportsdb.com/event/'+str(e.get('idEvent') or '')},
                 e.get('idEvent'),
                 home_team_id=e.get('idHomeTeam'),away_team_id=e.get('idAwayTeam'))
            if entry:found.append(entry)
        if found:break  # Avoid needless extra requests when any candidate exists.
    # TheSportsDB also indexes schedules by stable team IDs, even when
    # searchevents cannot resolve an alternate club spelling. A bounded
    # date+ID lookup is safe only for an already unambiguous registry pair.
    if not found:
        found.extend(_sportsdb_dated_id_event(fixture))
    return unique_fixture(found)


def unique_fixture(found):
    """Only one unambiguous event identity can vote; plausible variants are review-only.

    Duplicate appearances of the SAME provider event ID across date queries count once.
    Distinct provider event IDs remain ambiguous even when time/league agree.
    """
    if not found:return None
    unique={}
    for index,row in enumerate(found):
        event_id=row.get('_eventId')
        key=('event',event_id) if event_id else ('fallback',row.get('reference'),
             row.get('_identityHome'),row.get('_identityAway'),row.get('kickoff'))
        old=unique.get(key)
        if old is not None:
            # If one provider reuses an event ID with contradictory labels or
            # kickoff details, fail closed rather than hiding the contradiction.
            fields=('_identityHome','_identityAway','kickoff','country','league')
            if any(old.get(f)!=row.get(f) for f in fields):
                key=('contradictory_event_id',event_id,index)
        unique.setdefault(key,row)
    candidates=list(unique.values())
    if len(candidates)==1 and candidates[0].get('_identity')=='match':
        return candidates[0]
    return {'source':candidates[0]['source'], '_identityReview':True,
            '_identityReason':('multiple_possible_provider_events' if len(candidates)>1
                               else candidates[0].get('_identityReason','identity_requires_review')),
            '_reviewCandidates':candidates[:5]}


def espn(fixture, country=''):
    # ESPN dates are in UTC; search adjacent days to catch conversion boundaries.
    if country not in ESPN_LEAGUES:
        return None
    target = dt.date.fromisoformat(fixture['match_date'])
    matches = []
    # FA_PROVIDER_ROUTING_V1: a known competition narrows the ESPN country
    # search ONLY when it matches an explicit league mapping. An unknown alias
    # preserves the historical country-wide lookup rather than silently losing
    # possible matches. The hint is NOT a new verification vote.
    supported = ESPN_LEAGUES[country]
    competition_hint = league_key(fixture.get('league'))
    if competition_hint:
        narrowed = tuple(code for code in supported
                         if league_key(KNOWN_LEAGUES[code][1]) == competition_hint)
        if narrowed:
            supported = narrowed
    for league in supported:
        for day in (target, target-dt.timedelta(days=1), target+dt.timedelta(days=1)):
            key=(league,day.isoformat())
            if key in _ESPN_CACHE and time.time()-_ESPN_CACHE[key][0]<1800:
                data=_ESPN_CACHE[key][1]
            else:
                url = 'https://site.api.espn.com/apis/site/v2/sports/soccer/'+league+'/scoreboard?'+urlencode({'dates':day.strftime('%Y%m%d')})
                data = art.get_json(url)
                if len(_ESPN_CACHE)>100:_ESPN_CACHE.clear()
                _ESPN_CACHE[key]=(time.time(),data)
            for event in (data.get('events') or []):
                competitors = ((event.get('competitions') or [{}])[0].get('competitors') or [])
                home = next((x for x in competitors if x.get('homeAway')=='home'),{})
                away = next((x for x in competitors if x.get('homeAway')=='away'),{})
                home_name = (home.get('team') or {}).get('displayName') or ''
                away_name = (away.get('team') or {}).get('displayName') or ''
                c,l = KNOWN_LEAGUES[league]
                entry=_event_record(fixture,home_name,away_name,str(event.get('date') or '')[:10],
                    {'source':'ESPN','kickoff':when_utc(event.get('date')),
                     'country':c,'league':l,
                     'reference':'https://www.espn.com/soccer/match/_/gameId/'+str(event.get('id') or '')},
                    event.get('id'),
                    home_team_id=(home.get('team') or {}).get('id'),
                    away_team_id=(away.get('team') or {}).get('id'))
                if entry:matches.append(entry)
    return unique_fixture(matches)


def football_data(fixture, _country=''):
    token = os.environ.get('FA_FOOTBALL_DATA_TOKEN','').strip()
    if not token: return None
    day = dt.date.fromisoformat(fixture['match_date'])
    start, end = day-dt.timedelta(days=1), day+dt.timedelta(days=2)
    url='https://api.football-data.org/v4/matches?'+urlencode({'dateFrom':start.isoformat(),'dateTo':end.isoformat()})
    result=art.get_json(url,headers={'X-Auth-Token':token})
    found=[]
    for e in (result.get('matches') or []):
        if not isinstance(e, dict): continue
        home = (e.get('homeTeam') or {}).get('name')
        away = (e.get('awayTeam') or {}).get('name')
        comp=e.get('competition') or {}
        area=e.get('area') or {}
        entry=_event_record(fixture,home,away,str(e.get('utcDate') or '')[:10],
            {'source':'football-data.org','kickoff':when_utc(e.get('utcDate')),
             'country':clean(area.get('name') or (comp.get('area') or {}).get('name')),
             'league':clean(comp.get('name')),
             'reference':'https://www.football-data.org/'},e.get('id'),
            home_team_id=(e.get('homeTeam') or {}).get('id'),
            away_team_id=(e.get('awayTeam') or {}).get('id'))
        if entry:found.append(entry)
    return unique_fixture(found)


def vote(records, field, fixture):
    evidence=[]
    league_countries={}
    for rec in records:
        value=clean(rec.get(field))
        if value:
            evidence.append({'source':rec['source'],'value':value,'reference':rec.get('reference','')})
            league_countries[rec['source']]=rec.get('country','')
    def normalized(record):
        val=record['value']
        if field=='kickoff': return val
        if field=='country': return art.norm(val)
        return _league_vote_key(val,league_countries.get(record['source'],''))
    groups=defaultdict(list)
    for record in evidence:
        groups[normalized(record)].append(record)
    # Count each provider only once, and accept the largest 3/4 agreement.
    # A fourth dissenting result must not overrule a real three-source quorum.
    voted={rec['source'] for rec in evidence}
    unique=len(voted)==len(evidence)
    best=max(groups.values(),key=len,default=[])
    consensus=unique and len(best)>=3
    date_guard=False
    if consensus and field=='kickoff':
        try:
            date_guard=dt.date.fromisoformat(best[0]['value'][:10])!=dt.date.fromisoformat(fixture['match_date'])
        except ValueError:date_guard=True
        consensus=not date_guard
    dissent=[e['source'] for e in evidence if best and normalized(e)!=normalized(best[0])]
    message=(f'{len(best)} of {len(evidence)} independent sources agree'
             if consensus else
             'Matching times fall on a different date; review fixture identity' if date_guard else
             f'No 3-source quorum ({len(best)} matching of {len(evidence)} available)' if evidence else
             'No provider results available; use the scan controls to retry')
    return {'state':'verified' if consensus else 'review',
            'value':best[0]['value'] if consensus else '',
            'evidence':evidence,'votes':len(best),'responded':len(evidence),'possible':4,
            'dissent':dissent,'message':message}


# Source-code search routes only. SW1 and CL1 have previously approved local
# examples; PT1 is a bounded Portugal search hypothesis, not verified identity.
# Never infer a route from an arbitrary code prefix or a team's nationality.
_SOURCE_CODE_ESPN_ROUTES = {'PT1':'Portugal','SW1':'Sweden','CL1':'Chile'}


def _source_code_espn_route(fixture, approved_league=''):
    if clean(fixture.get('country')) or clean(fixture.get('league')):
        return ''
    country=_SOURCE_CODE_ESPN_ROUTES.get(str(fixture.get('source_competition_code') or '').strip(), '')
    if approved_league and country:
        if not any(league_key(KNOWN_LEAGUES[code][1])==league_key(approved_league)
                   for code in ESPN_LEAGUES.get(country,())):
            return ''
    return country


def _api_plan_date_retry(fixture, error, now=None):
    """Provider-reported forward date restriction; no inferred fixed plan limit."""
    text = str(error)
    if 'Free plans do not have access to this date' not in text:
        return None
    window = re.search(r'from (\d{4}-\d{2}-\d{2}) to (\d{4}-\d{2}-\d{2})', text)
    if not window:
        return None
    try:
        start, end = (dt.date.fromisoformat(x) for x in window.groups())
        target = dt.date.fromisoformat(str(fixture.get('match_date') or ''))
        now = now or dt.datetime.now(dt.timezone.utc)
        if start > end or target <= end:
            return None
        days = (target-end).days
        retry_day = now.date()+dt.timedelta(days=days)
        return {'retryAfter':int(dt.datetime.combine(retry_day,dt.time.min,tzinfo=dt.timezone.utc).timestamp()),
                'allowedFrom':start.isoformat(),'allowedTo':end.isoformat()}
    except (ValueError,TypeError,OverflowError):
        return None


def _retain_api_date_deferral(old, health, now):
    # Record the current failure honestly; carry forward only a still-future
    # provider-reported window across a transport/quota failure, never a vote.
    if not old:return
    try:
        prior=json.loads(old['values_json']).get('providerHealth',{}).get('core',{}).get('API-Football',{})
        event=health.get('core',{}).get('API-Football',{})
        if event.get('status')!='error' or event.get('reason')=='date_outside_plan_window':
            return
        if event.get('reason') not in ('URLError','TimeoutError','ConnectionError','ConnectionResetError','HTTPError','RuntimeError','OSError'):
            return
        window=prior if prior.get('reason')=='date_outside_plan_window' else prior.get('dateDeferral',{})
        retry=window.get('retryAfter')
        if not isinstance(retry,int) or not now<retry:return
        start,end=(dt.date.fromisoformat(window[k]) for k in ('allowedFrom','allowedTo'))
        if start>end:return
        event['dateDeferral']={'retryAfter':retry,'allowedFrom':start.isoformat(),'allowedTo':end.isoformat()}
    except (ValueError,TypeError,AttributeError,KeyError):
        return


def _fixture_retry_due(old, now):
    if not old or now-old['checked_at'] >= RETRY:
        return True
    try:
        info=json.loads(old['values_json']).get('providerHealth',{}).get('core',{}).get('API-Football',{})
        window=info if info.get('reason')=='date_outside_plan_window' else info.get('dateDeferral',{})
        retry=window.get('retryAfter')
        return (
                isinstance(retry,int) and old['checked_at']<retry<=now)
    except (ValueError,TypeError,AttributeError,KeyError):
        return False


def _manual_identity(decisions, field):
    """An existing explicit approval is a routing hint, NEVER a provider vote."""
    decision = (decisions or {}).get(field, {})
    return clean(decision.get('value')) if decision.get('state') == 'manual' else ''


def _provider_skip_reason(name, country_hint):
    """Conservative per-adapter eligibility. Does not make a network request."""
    if name == 'API-Football' and not art.api_football_key():
        return 'credential_not_configured'
    if name == 'football-data.org' and not os.environ.get('FA_FOOTBALL_DATA_TOKEN', '').strip():
        return 'credential_not_configured'
    if name == 'ESPN':
        if not country_hint:
            return 'country_not_known'
        if country_hint not in ESPN_LEAGUES:
            return 'country_not_mapped'
    return ''



# Only the result of this internal two-source proof may trigger a second pass.
_TWO_SOURCE_COUNTRY_TOKEN = object()

def _two_provider_country_evidence(fixture, events):
    """Return bounded country routing proof, not an identity approval or vote.

    Requires distinct LIVE providers to report one unique event each, with
    real team IDs independently mapping to the same Reep home/away pair.
    UTC day, kickoff, competition, team categories and source country agree.
    Unresolved, contradictory or missing evidence leaves the fixture as-is.
    """
    if clean(fixture.get('country')) or not team_registry.DB.is_file():
        return None
    source_map={'API-Football':'api_football','football-data.org':'football_data_org',
                'TheSportsDB':'thesportsdb','ESPN':'espn'}
    valid=[]
    try:
        uri='file:'+str(team_registry.DB.resolve())+'?mode=ro'
        with closing(sqlite3.connect(uri,uri=True,timeout=12)) as c:
            c.row_factory=sqlite3.Row
            for event in events:
                provider=source_map.get(event.get('source'))
                ids=event.get('_providerTeamIds')
                country=clean(event.get('country'))
                league=clean(event.get('league'))
                kickoff=clean(event.get('kickoff'))
                day=clean(event.get('_eventDate'))
                if (not provider or not ids or len(ids)!=2 or
                    not all(ids) or not country or not league or
                    not event.get('_eventId') or day!=fixture.get('match_date') or
                    not re.fullmatch(r'\d{4}-\d\d-\d\d \d\d:\d\d',kickoff) or
                    kickoff[:10]!=fixture.get('match_date')):
                    continue
                participant_ids=[]
                category_ok=True
                for external,original,seen in zip(ids,
                        (fixture.get('home'),fixture.get('away')),
                        (event.get('_identityHome'),event.get('_identityAway'))):
                    rows=c.execute("""SELECT t.team_id,t.canonical_name,t.country_key,
                                  t.category,t.gender FROM provider_ids p
                               JOIN teams t ON t.team_id=p.team_id
                              WHERE p.provider=? AND p.namespace='team'
                                AND p.external_id=? AND t.source='Reep'""",
                                   (provider,str(external))).fetchall()
                    if len(rows)!=1:
                        category_ok=False;break
                    row=rows[0]
                    group=team_registry._class(row['canonical_name'],row['category'],row['gender'])
                    if (team_registry._country(row['country_key'])!=team_registry._country(country)
                        or team_registry._class(original)!=group
                        or team_registry._class(seen)!=group):
                        category_ok=False;break
                    participant_ids.append(row['team_id'])
                if not category_ok or len(participant_ids)!=2 or participant_ids[0]==participant_ids[1]:
                    continue
                # A provider must also satisfy the current strict identity
                # resolver when evaluated against its own asserted country.
                # Its assertion becomes only a RESEARCH CANDIDATE here.
                probe=_provider_event({**fixture,'country':country},
                    event.get('_identityHome'),event.get('_identityAway'),day,
                    country=country,league=league,provider_team_ids=ids,
                    provider_id_source=provider)
                if probe.classification!='match':
                    continue
                key=(team_registry._country(country),league_key(league),
                     kickoff,*participant_ids)
                valid.append((event['source'],country,key,event['_eventId']))
    except (sqlite3.Error,OSError,ValueError,TypeError,KeyError):
        return None
    if len(valid)<2 or len({v[0] for v in valid})!=len(valid):
        return None
    if len({v[2] for v in valid})!=1:
        return None
    return {'country':valid[0][1],
            'providers':tuple(sorted(v[0] for v in valid)),
            'provedEventIds':{v[0]:v[3] for v in valid},
            'provedLeague':valid[0][2][1],
            'provedKickoff':valid[0][2][2]}


def _countryless_ambiguous_senior_research_pair(fixture):
    """One potential cross-provider senior pair for review, NEVER an alias approval.

    Each raw name must have ONE and only one exact Reep senior men claim,
    globally across countries; other category claims may exist, but keep this
    research review-only. Both clubs must have exactly one source TEAM ID in
    each of ESPN and TheSportsDB. No fuzzy matching or new identity rows.
    """
    if clean(fixture.get('country')) or clean(fixture.get('league')):
        return None
    try:
        dt.date.fromisoformat(str(fixture.get('match_date') or ''))
    except (ValueError,TypeError):
        return None
    if any(team_registry._class(fixture.get(side)) for side in ('home','away')):
        return None
    if not team_registry.DB.is_file():
        return None
    candidates=[]
    collision=False
    try:
        uri='file:'+str(team_registry.DB.resolve())+'?mode=ro'
        with closing(sqlite3.connect(uri,uri=True,timeout=9)) as c:
            c.row_factory=sqlite3.Row
            for side in ('home','away'):
                key=team_registry.norm(fixture.get(side))
                if not key or len(key)<7:return None
                rows=c.execute("""SELECT DISTINCT t.team_id,t.canonical_name,
                    t.country_key,t.category,t.gender FROM aliases a
                   JOIN teams t ON t.team_id=a.team_id
                  WHERE a.name_key=? AND a.source='Reep' AND t.source='Reep'
                  LIMIT 102""",(key,)).fetchall()
                if not rows or len(rows)>100:return None
                senior=[r for r in rows if r['gender']=='men' and
                        not r['category'] and
                        not team_registry._class(r['canonical_name'],r['category'],r['gender'])]
                if len({r['team_id'] for r in senior})!=1:return None
                chosen=senior[0]
                if not chosen['country_key']:return None
                if any(team_registry._class(r['canonical_name'],r['category'],r['gender'])
                       for r in rows):
                    collision=True
                mapped={}
                for provider in ('espn','thesportsdb'):
                    ids=c.execute("""SELECT external_id FROM provider_ids
                         WHERE team_id=? AND provider=? AND namespace='team'
                         LIMIT 3""",(chosen['team_id'],provider)).fetchall()
                    if len(ids)!=1 or not ids[0]['external_id']:return None
                    mapped[provider]=ids[0]['external_id']
                candidates.append({'team_id':chosen['team_id'],
                    'canonical':chosen['canonical_name'],
                    'country_key':chosen['country_key'],'ids':mapped})
    except (sqlite3.Error,OSError,TypeError,ValueError):
        return None
    if (not collision or len(candidates)!=2
        or candidates[0]['country_key']!=candidates[1]['country_key']
        or candidates[0]['team_id']==candidates[1]['team_id']):
        return None
    ckey=candidates[0]['country_key']
    # Only one already-configured ESPN league route is allowed in this small
    # ambiguity-safe research path; never enumerate leagues or countries.
    countries=[name for name,codes in ESPN_LEAGUES.items()
               if team_registry._country(name)==ckey and len(codes)==1]
    if len(countries)!=1:return None
    country=countries[0]
    slug=ESPN_LEAGUES[country][0]
    if KNOWN_LEAGUES.get(slug,('',''))[0]!=country:return None
    return {'country':country,'league':KNOWN_LEAGUES[slug][1],
            'names':tuple(x['canonical'] for x in candidates),
            'mapped_ids':{p:tuple(x['ids'][p] for x in candidates)
                          for p in ('espn','thesportsdb')}}


def _countryless_ambiguous_fixture_research(fixture):
    """Bounded TWO-provider event discovery, visible only as REVIEW evidence.

    The Reep candidate pair selects retrieval terms; it never licenses
    country, gender, category or alias verification. Both returned events
    must satisfy the original ID+date+country+league+kickoff proof. Even a
    successful proof cannot cast votes while original category is ambiguous.
    """
    pair=_countryless_ambiguous_senior_research_pair(fixture)
    if not pair:return None
    home,away=pair['names']
    research_fixture={**fixture,'home':home,'away':away,
                      'country':pair['country'],'league':pair['league']}
    probes=[]
    for name,fn in (('ESPN',espn),('TheSportsDB',sportsdb)):
        try:
            event=fn(research_fixture,pair['country'])
        except Exception:
            return None  # Research-only unavailability cannot break the scan.
        if (not isinstance(event,dict) or event.get('_identity')!='match'
            or event.get('source')!=name or event.get('_identityReview')
            or tuple(event.get('_providerTeamIds') or ())!=pair['mapped_ids'][
                'espn' if name=='ESPN' else 'thesportsdb']):
            return None
        probes.append(event)
    proof=_two_provider_country_evidence(fixture,probes)
    if (not proof or set(proof['providers'])!={'ESPN','TheSportsDB'}
        or team_registry._country(proof['country'])!=
             team_registry._country(pair['country'])):
        return None
    return {'country':proof['country'],'providers':proof['providers'],
            'events':probes, 'proof':proof}


def _countryless_crossday_espn_research(fixture, *, fetcher=None):
    """One countryless prior-UTC-day ESPN EVENT for human review only.

    Neither proposed Reep aliases nor provider IDs license a fixture vote,
    a country/category approval, or a change to the raw SoccerRating date.
    One existing country and one ESPN league are used solely to bound lookup.
    An explicit UTC time must fall on the previous day AND have the source
    calendar date in Europe/Berlin. This is a hypothesis, not source policy.
    """
    if clean(fixture.get('country')) or clean(fixture.get('league')):
        return None
    if any(team_registry._class(fixture.get(side)) for side in ('home', 'away')):
        return None
    try:
        source_day = dt.date.fromisoformat(str(fixture.get('match_date') or ''))
    except (ValueError, TypeError):
        return None
    if not team_registry.DB.is_file():
        return None
    found = []
    try:
        uri = 'file:' + str(team_registry.DB.resolve()) + '?mode=ro'
        with closing(sqlite3.connect(uri, uri=True, timeout=9)) as c:
            c.row_factory = sqlite3.Row
            for side in ('home', 'away'):
                name_key = team_registry.norm(fixture.get(side))
                if len(name_key) < 7:
                    return None
                # Require a UNIQUE Reep source identity across EVERY category.
                # Proposed aliases are search hints only, never approvals.
                rows = c.execute("""SELECT DISTINCT t.team_id,t.canonical_name,
                           t.country_key,t.gender,t.category
                      FROM aliases a JOIN teams t ON t.team_id=a.team_id
                     WHERE a.name_key=? AND a.source='Reep' AND t.source='Reep'
                     LIMIT 4""", (name_key,)).fetchall()
                if len(rows) != 1:
                    return None
                record = rows[0]
                if (record['gender'] != 'men' or record['category']
                    or team_registry._class(record['canonical_name'],
                                            record['category'],record['gender'])
                    or not record['country_key']):
                    return None
                ids = c.execute("""SELECT external_id FROM provider_ids
                      WHERE team_id=? AND provider='espn' AND namespace='team'
                      LIMIT 3""", (record['team_id'],)).fetchall()
                if len(ids) != 1 or not ids[0]['external_id']:
                    return None
                found.append((record['team_id'],record['country_key'],
                              str(ids[0]['external_id'])))
    except (sqlite3.Error, OSError, ValueError, TypeError):
        return None
    if (len(found) != 2 or found[0][0] == found[1][0]
        or found[0][1] != found[1][1] or found[0][2] == found[1][2]):
        return None
    countries = [(name,codes[0]) for name,codes in ESPN_LEAGUES.items()
                 if len(codes) == 1
                 and team_registry._country(name) == found[0][1]]
    if len(countries) != 1:
        return None
    country, league_code = countries[0]
    if KNOWN_LEAGUES.get(league_code, ('', ''))[0] != country:
        return None
    utc_day = source_day - dt.timedelta(days=1)
    url = ('https://site.api.espn.com/apis/site/v2/sports/soccer/'
           + league_code + '/scoreboard?' + urlencode({'dates':utc_day.strftime('%Y%m%d')}))
    try:
        from zoneinfo import ZoneInfo
        data = (fetcher or art.get_json)(url)
        events = (data.get('events') or []) if isinstance(data, dict) else []
        matches = []
        for event in events[:80]:
            if not isinstance(event, dict) or not event.get('id'):
                continue
            try:
                kickoff = dt.datetime.fromisoformat(
                    str(event.get('date') or '').replace('Z', '+00:00'))
                if kickoff.tzinfo is None:
                    continue
                timestamp = kickoff.astimezone(dt.timezone.utc)
                local_day = timestamp.astimezone(ZoneInfo('Europe/Berlin')).date()
            except (ValueError, TypeError, KeyError):
                continue
            if timestamp.date() != utc_day or local_day != source_day:
                continue
            competitors = ((event.get('competitions') or [{}])[0]
                           .get('competitors') or [])
            home = next((p.get('team') or {} for p in competitors
                         if p.get('homeAway') == 'home'), {})
            away = next((p.get('team') or {} for p in competitors
                         if p.get('homeAway') == 'away'), {})
            if (str(home.get('id') or '') != found[0][2]
                or str(away.get('id') or '') != found[1][2]):
                continue
            matches.append({'status':'single_provider_cross_day_review_only',
                            'country':country,'league':KNOWN_LEAGUES[league_code][1],
                            'kickoff':timestamp.strftime('%Y-%m-%d %H:%M'),
                            'sourceDate':source_day.isoformat(),
                            'sourceUTCDate':timestamp.date().isoformat(),
                            'displayDateEuropeBerlin':local_day.isoformat(),
                            'sourceEventId':str(event['id'])[:90],
                            'sourceTeamIds':[found[0][2],found[1][2]],
                            'sourceHome':clean(home.get('displayName')),
                            'sourceAway':clean(away.get('displayName')),
                            'reference':'https://www.espn.com/soccer/match/_/gameId/'
                                        + str(event['id'])[:90]})
        # No identity if even two apparently plausible source event IDs exist.
        return matches[0] if len(matches) == 1 else None
    except (OSError, ValueError, TypeError, KeyError):
        return None


def evaluate(fixture, *, providers=None, approved_identity=None, include_health=False, _route_proof=None):
    """Evaluate four independent core votes; optionally report adapter outcomes.

    `approved_identity` is only a routing hint. It is NOT appended to records,
    evidence or quorum. `include_health` adds a third return value for scanner
    observability; legacy callers continue receiving (fields, errors).
    Status 'attempted' indicates adapter invocation, not a confirmed HTTP call.
    """
    if _route_proof is not None and _route_proof[0] is not _TWO_SOURCE_COUNTRY_TOKEN:
        raise ValueError('Unverified internal country route')
    using_default_providers = providers is None
    if providers is None:
        providers = {'API-Football': api_football, 'TheSportsDB': sportsdb,
                     'ESPN': espn, 'football-data.org': football_data}
    records = []
    identity_reviews = []
    research_events = []
    errors = {}
    events = {}
    approved_country = _manual_identity(approved_identity, 'country')
    approved_league = _manual_identity(approved_identity, 'league')
    research_country = clean(_route_proof[1]['country']) if _route_proof else ''
    hint = approved_country or clean(fixture.get('country')) or research_country
    origin = ('approved' if approved_country else
              'fixture' if clean(fixture.get('country')) else
              'two_provider_id_agreement' if research_country else 'unknown')
    route = {'countryHint': hint, 'countryOrigin': origin,
             'leagueHint': approved_league, 'leagueOrigin': 'approved' if approved_league else 'unknown',
             'note': 'Routing hints are not votes; one adapter invocation may contain multiple requests.'}
    code_country = '' if (approved_country or _route_proof) else _source_code_espn_route(fixture,approved_league)
    if code_country:
        route['sourceCompetitionRoute']={'code':fixture['source_competition_code'],
            'country':code_country,'provider':'ESPN','reviewOnly':True}
    pair_route={}
    if not hint and not code_country and not approved_league and not clean(fixture.get('league')) and not fixture.get('source_competition_code'):
        pair_route=team_registry.research_pair_route(fixture.get('home'),fixture.get('away'))
        if pair_route.get('country') in ESPN_LEAGUES:
            route['registrySearchRoute']={**pair_route,'provider':'ESPN'}
        else:pair_route={}
    if _route_proof:
        route['researchProviders']=list(_route_proof[1]['providers'])
        route['reusedProviderResults']=sorted(_route_proof[1].get('reuseMatched',{}))
    for name in SOURCES:
        fn = providers.get(name)
        if fn is None:
            events[name] = {'status': 'skipped', 'reason': 'adapter_not_supplied',
                            'attempted': False, 'durationMs': 0, 'fields': []}
            continue
        # Injected test providers are deliberately exempt from environment-based
        # eligibility checks, allowing full deterministic tests without keys.
        research_only = name == 'ESPN' and not hint and bool(code_country or pair_route)
        adapter_hint = (code_country or pair_route.get('country')) if research_only else hint
        skipped = _provider_skip_reason(name, adapter_hint) if using_default_providers else ''
        if skipped:
            events[name] = {'status': 'skipped', 'reason': skipped,
                            'attempted': False, 'durationMs': 0, 'fields': []}
            continue
        started = time.monotonic()
        try:
            request_fixture = fixture
            # A manually approved country is independent fixture identity
            # context, not a provider vote. Use it only if SoccerRating's
            # original country is empty; never override a conflicting country.
            if (approved_country or research_country) and not clean(fixture.get('country')):
                request_fixture = {**request_fixture,
                                   'country':approved_country or research_country}
            if name == 'ESPN' and approved_league:
                request_fixture = {**request_fixture, 'league': approved_league}
            # Reuse only a FULLY MATCHED, same-event first-pass response whose
            # immutable source fields were checked against the two-ID proof.
            # Review candidates, missing IDs and conflicting evidence always
            # run through the normal adapter again.
            reused = (_route_proof[1].get('reuseMatched',{}).get(name)
                      if _route_proof else None)
            record = reused if reused is not None else fn(request_fixture, adapter_hint)
            elapsed = max(0, round((time.monotonic() - started) * 1000))
            if record:
                if not isinstance(record, dict) or record.get('source') != name:
                    raise ValueError('Provider identity mismatch')
                if research_only:
                    # The search hypothesis cannot license an alias bridge,
                    # bootstrap country proof, or contribute any quorum vote.
                    candidates=(record.get('_reviewCandidates') or []) if record.get('_identityReview') else [record]
                    reason='source_code_route_review_only' if code_country else 'registry_country_route_review_only'
                    identity_reviews.extend({**candidate,'_identityReason':reason} for candidate in candidates[:5])
                    events[name]={'status':'identity_review','reason':reason,
                        'attempted':True,'durationMs':elapsed,'fields':[]}
                    continue
                if record.get('_identityReview'):
                    candidates=record.get('_reviewCandidates') or []
                    if (len(candidates)==1 and
                        record.get('_identityReason')!='multiple_possible_provider_events'):
                        research_events.append(candidates[0])
                    identity_reviews.extend(candidates[:5])
                    events[name] = {'status': 'identity_review',
                                    'reason':record.get('_identityReason','identity_requires_review'),
                                    'attempted':True,'durationMs':elapsed,'fields':[]}
                    continue
                records.append(record)
                research_events.append(record)
                values = [field for field in ('kickoff', 'country', 'league') if clean(record.get(field))]
                events[name] = {'status': 'matched', 'reason': 'fixture_identity_matched',
                                'attempted': True, 'durationMs': elapsed, 'fields': values,
                                'reusedFirstPass': reused is not None}
                if not hint and record.get('country') in ESPN_LEAGUES:
                    hint = record['country']
                    route['countryHint'] = hint
                    route['countryOrigin'] = 'provider_research'
                elif not hint and name == 'TheSportsDB':
                    key = league_key(record.get('league', ''))
                    countries = {v[0] for v in KNOWN_LEAGUES.values() if league_key(v[1]) == key}
                    if len(countries) == 1:
                        hint = next(iter(countries))
                        route['countryHint'] = hint
                        route['countryOrigin'] = 'competition_mapping'
            else:
                events[name] = {'status': 'no_match', 'reason': 'no_unambiguous_fixture',
                                'attempted': True, 'durationMs': elapsed, 'fields': []}
        except Exception as exc:
            # Match pre-existing error behavior; telemetry stores only error
            # class names, never credentials, request headers or full URLs.
            detail = (str(exc) if isinstance(exc, (ValueError, RuntimeError))
                      else type(exc).__name__)[:150]
            errors[name] = detail + (' HTTP ' + str(getattr(exc, 'code'))
                                     if getattr(exc, 'code', None) else '')
            events[name] = {'status': 'error', 'reason': type(exc).__name__,
                            'attempted': True,
                            'durationMs': max(0, round((time.monotonic() - started) * 1000)),
                            'fields': []}
            if name=='API-Football':
                deferred=_api_plan_date_retry(fixture,exc)
                if deferred:
                    events[name].update(reason='date_outside_plan_window',**deferred)
    fields = {field: vote(records, field, fixture) for field in ('kickoff', 'country', 'league')}
    for review in identity_reviews:
        for field in ('kickoff','country','league'):
            value=clean(review.get(field))
            if not value:continue
            fields[field]['evidence'].append({
                'source':review['source'],'value':value,'reference':review.get('reference',''),
                'identityReview':True,'identityReason':review.get('_identityReason','requires_review'),
                'sourceHome':review.get('_identityHome',''),
                'sourceAway':review.get('_identityAway','')})
    # One bounded second pass when TWO independently observed provider events
    # prove both participant IDs, orientation, competition, kickoff and country.
    # Research evidence itself has ZERO votes. Only final matched events vote.
    if not approved_country and not clean(fixture.get('country')) and not _route_proof:
        evidence=_two_provider_country_evidence(fixture,research_events)
        if evidence:
            # Only events with an ID in the independently checked source proof
            # can be retained; each source still contributes at most ONE vote.
            kept={}
            for record in records:
                provider=record.get('source')
                if (provider in evidence['provedEventIds']
                    and record.get('_eventId')==evidence['provedEventIds'][provider]
                    and team_registry._country(record.get('country'))==
                        team_registry._country(evidence['country'])
                    and league_key(record.get('league'))==evidence['provedLeague']
                    and clean(record.get('kickoff'))==evidence['provedKickoff']):
                    kept[provider]=record
            evidence['reuseMatched']=kept
            return evaluate(fixture,providers=providers if not using_default_providers else None,
                            approved_identity=approved_identity,include_health=include_health,
                            _route_proof=(_TWO_SOURCE_COUNTRY_TOKEN,evidence))
    # When the original queue has NO country, league, or independent category
    # identity, ID-anchored senior events may be retrieved for REVIEW ONLY.
    # Never put these events in records or research_events: they cannot
    # trigger a second pass or count toward a three-source quorum.
    if (using_default_providers and not _route_proof and not approved_country
        and not clean(fixture.get('country')) and not clean(fixture.get('league'))
        and not records and not research_events):
        research=_countryless_ambiguous_fixture_research(fixture)
        if research:
            route['countrylessResearch']={
                'status':'two_provider_review_only',
                'country':research['country'],
                'sources':list(research['providers']),
                'reason':'original_fixture_participant_category_unconfirmed',
                'events':[{
                    'source':rec['source'],
                    'eventId':str(rec.get('_eventId') or ''),
                    'sourceHome':clean(rec.get('_identityHome')),
                    'sourceAway':clean(rec.get('_identityAway')),
                    'providerTeamIds':[str(x) for x in
                                       (rec.get('_providerTeamIds') or ())]
                } for rec in research['events']]}
            for field in ('kickoff','country','league'):
                for rec in research['events']:
                    value=clean(rec.get(field))
                    if value:
                        fields[field]['evidence'].append({
                            'source':rec['source'],'value':value,
                            'reference':rec.get('reference',''),
                            'identityReview':True,
                            'countrylessResearch':True,
                            'identityReason':'original_category_unconfirmed',
                            'sourceEventId':str(rec.get('_eventId') or ''),
                            'sourceTeamIds':[str(x) for x in
                                             (rec.get('_providerTeamIds') or ())],
                            'sourceHome':clean(rec.get('_identityHome')),
                            'sourceAway':clean(rec.get('_identityAway'))})
    # Bounded prior-UTC-day lookup for a countryless fixture. Reep identity
    # and ESPN provider IDs are research ROUTING HINTS only, not votes or
    # approval of the original SoccerRating participant category/timezone.
    # This branch runs only when the ordinary provider search and existing
    # two-provider same-day research have both failed to find an event.
    if (using_default_providers and not _route_proof and not approved_country
        and not approved_league and not clean(fixture.get('country'))
        and not clean(fixture.get('league')) and not records
        and not research_events and not route.get('countrylessResearch')):
        crossday = _countryless_crossday_espn_research(fixture)
        if crossday:
            route['countrylessResearch'] = {
                'status': 'single_provider_cross_day_review_only',
                'reason': 'source_display_timezone_and_participant_category_unconfirmed',
                'country': crossday['country'], 'sources': ['ESPN'],
                'sourceDate': crossday['sourceDate'],
                'sourceUTCDate': crossday['sourceUTCDate'],
                'displayDateEuropeBerlin': crossday['displayDateEuropeBerlin'],
                'sourceEventId': crossday['sourceEventId'],
                'sourceTeamIds': crossday['sourceTeamIds']}
            for field in ('kickoff', 'country', 'league'):
                fields[field]['evidence'].append({
                    'source':'ESPN', 'value':crossday[field],
                    'reference':crossday['reference'],
                    'identityReview':True, 'countrylessResearch':True,
                    'dateBoundaryResearch':True,
                    'identityReason':('Possible UTC/CET date boundary: original '
                                      + crossday['sourceDate'] + ', ESPN UTC '
                                      + crossday['sourceUTCDate']
                                      + '; timezone and category unconfirmed'),
                    'sourceEventId':crossday['sourceEventId'],
                    'sourceTeamIds':crossday['sourceTeamIds'],
                    'sourceHome':crossday['sourceHome'],
                    'sourceAway':crossday['sourceAway']})
    if include_health:
        return fields, errors, {'core': events, 'routing': route, 'version': 1}
    return fields, errors



def flag_candidates(country):
    """Compare up to four image-service copies before saving a country flag.

    A REST Countries response supplies ISO2 for address formation only; it is
    NOT counted as an image vote. If a service fails or images differ, manual
    review is required. Avoid fictional third-site consensus.
    """
    if not re.fullmatch(r"[\w .'-]{2,70}",country,flags=re.U):return [],'Invalid country for image search.'
    # FA_AFC_ASIA_REGIONAL_MARKER_V1: geographic region has NO national flag.
    if art.norm(country) == "asia":
        return official_review.asia_badge_candidates("Asia", FLAGS)
    # Recognized home nations have subdivision flags rather than ISO alpha-2
    # country flags. Show available candidates for manual selection, never
    # invent three votes from providers that do not support subdivisions.
    home_nations={'england':'gb-eng','scotland':'gb-sct','wales':'gb-wls'}
    # Known ISO 3166-1 country names avoid a fragile mandatory network lookup.
    # This mapping does not verify that a fixture belongs to that country.
    known_iso = {
        'japan':'jp','ghana':'gh','germany':'de','france':'fr','spain':'es',
        'italy':'it','portugal':'pt','netherlands':'nl','belgium':'be',
        'austria':'at','switzerland':'ch','denmark':'dk','sweden':'se','belarus':'by',
        'norway':'no','finland':'fi','iceland':'is','ireland':'ie',
        'united states':'us','united states of america':'us',
        'canada':'ca','mexico':'mx','brazil':'br','argentina':'ar',
        'chile':'cl','colombia':'co','uruguay':'uy','paraguay':'py',
        'peru':'pe','ecuador':'ec','bolivia':'bo','venezuela':'ve',
        'south korea':'kr','republic of korea':'kr','china':'cn',
        'australia':'au','new zealand':'nz','india':'in','thailand':'th',
        'vietnam':'vn','indonesia':'id','malaysia':'my','singapore':'sg',
        'saudi arabia':'sa','united arab emirates':'ae','qatar':'qa',
        'turkey':'tr','türkiye':'tr','greece':'gr','poland':'pl',
        'ukraine':'ua','croatia':'hr','serbia':'rs','czechia':'cz',
        'czech republic':'cz','slovakia':'sk','romania':'ro','hungary':'hu',
        'south africa':'za','nigeria':'ng','cameroon':'cm','egypt':'eg',
        'morocco':'ma','tunisia':'tn','algeria':'dz','senegal':'sn',
        'ivory coast':'ci','côte d’ivoire':'ci','cote d ivoire':'ci',
        'kenya':'ke','uganda':'ug','tanzania':'tz','zambia':'zm',
        'zimbabwe':'zw','ethiopia':'et','israel':'il','cyprus':'cy',
        'georgia':'ge','armenia':'am','azerbaijan':'az','russia':'ru',
        'kazakhstan':'kz','uzbekistan':'uz','iran':'ir','iraq':'iq',
        'pakistan':'pk','bangladesh':'bd','nepal':'np','sri lanka':'lk'
    }
    subdivision=home_nations.get(art.norm(country))
    if subdivision:
        iso=subdivision
    else:
        iso=known_iso.get(art.norm(country), '')
        if not iso:
            try:
                uri='https://restcountries.com/v3.1/name/'+__import__('urllib.parse',fromlist=['quote']).quote(country)+'?fullText=true&fields=name,cca2'
                rows=art.get_json(uri)
                if isinstance(rows,dict) and rows.get('cca2'):rows=[rows]
                if not isinstance(rows,list) or len(rows)!=1:
                    return [],'Country code not uniquely recognized.'
                rec=rows[0]
                iso=clean(rec.get('cca2')).lower()
                country_name=clean((rec.get('name') or {}).get('common'))
                if not re.fullmatch(r'[a-z]{2}',iso) or not art.country_match(country,country_name):
                    return [],'Country code conflicts with supplied name.'
            except Exception as exc:
                return [],'Country-code lookup unavailable: '+type(exc).__name__
    # Four legacy image services are retained; a public-domain REST Countries
    # flag is an ADDITIONAL manual candidate only, not an extra independent vote.
    # Several CDNs republish the same flags; never inflate verification counts.
    sources=[('FlagCDN','https://flagcdn.com/w80/'+iso+'.png')]
    if not subdivision:
        sources.extend([
            ('FlagsAPI','https://flagsapi.com/'+iso.upper()+'/flat/64.png'),
            ('FlagsCenter','https://flagscenter.com/api/v1/'+iso+'/128.png')])
    try:
        title='File:Flag of '+country+'.svg'
        commons=art.get_json('https://commons.wikimedia.org/w/api.php?'+urlencode({
            'action':'query','format':'json','titles':title,'prop':'imageinfo',
            'iiprop':'url','iiurlwidth':160}))
        pages=(commons.get('query') or {}).get('pages') or {}
        imgs=[im for page in pages.values() for im in page.get('imageinfo',[])]
        uri=(imgs[0].get('thumburl') or '') if imgs else ''
        if uri:sources.append(('Wikimedia Commons',uri))
    except Exception:pass
    # REST Countries supplies public-domain flag artwork. This channel is
    # always available as a review candidate when the identity code is known;
    # it is explicitly excluded from automatic flag-consensus votes.
    if not subdivision:
        sources.append(('REST Countries (manual)',
                        'https://flags.restcountries.com/v5/w160/'+iso+'.png'))
    found=[];errors=[]
    for name,url in sources:
        try:
            png=art.rasterize(art.retrieve(url))
            digest=hashlib.sha256(png).hexdigest()
            dest=FLAGS/(digest+'.png')
            if not dest.exists():dest.write_bytes(png)
            found.append({'source':name,'value':country+' national flag','id':digest,
                          'image':'/fixture-flag-image/'+digest+'.png','reference':url,
                          'imageData':png})
        except Exception as exc:errors.append(name+': '+type(exc).__name__)
    from itertools import combinations
    winner=[]
    vote_candidates=[x for x in found if x['source']!='REST Countries (manual)']
    for size in range(len(vote_candidates),2,-1):
        for subset in combinations(vote_candidates,size):
            if all(art.same_artwork(a['imageData'],b['imageData'])
                   for a,b in combinations(subset,2)):
                winner=list(subset)
                break
        if winner:break
    winner_sources={x['source'] for x in winner}
    ordered=winner+[x for x in found if x['source'] not in winner_sources]
    for it in ordered:it.pop('imageData')
    return ordered,(f'{len(winner)} of {len(vote_candidates)} flag-image services agree on artwork'
        if len(winner)>=3 else 'Flag artwork needs manual review ('+
        ', '.join(errors or ['fewer than three matching images'])+').')


def flag_image(image_id):
    if not re.fullmatch(r'[a-f0-9]{64}',image_id):return None
    with LOCK,closing(get_conn()) as c:
        for row in c.execute('SELECT values_json FROM fixture_checks LIMIT 300'):
            fields=json.loads(row[0]); candidates=fields.get('countryLogo',{}).get('evidence',[])
            if any(x.get('id')==image_id for x in candidates):
                target=FLAGS/(image_id+'.png')
                if target.is_file() and target.stat().st_size<art.MAX_BYTES:return target.read_bytes()
    return None


def approve_flag(identifier,candidate_id,queue_supplier,save_logo,country_logos):
    if not isinstance(identifier,str) or not re.fullmatch(r'sr_[a-f0-9]{24}',identifier):
        raise ValueError('Invalid fixture ID.')
    if not isinstance(candidate_id,str) or not re.fullmatch(r'[a-f0-9]{64}',candidate_id):
        raise ValueError('Invalid flag selection.')
    if identifier not in {r['id'] for r in queue_supplier()}:
        raise ValueError('Fixture is no longer pending.')
    with LOCK,closing(get_conn()) as c:
        row=c.execute('SELECT * FROM fixture_checks WHERE id=?',(identifier,)).fetchone()
        if not row: raise ValueError('Search the fixture first.')
        fields=json.loads(row['values_json']); decisions=json.loads(row['decisions_json'])
        country=decisions.get('country',{}).get('value') or _effective_country(identifier,fields,decisions).get('value')
        if not country: raise ValueError('Approve the country before the national flag.')
        choices=fields.get('countryLogo',{}).get('evidence',[])
        candidate=next((x for x in choices if x.get('id')==candidate_id),None)
        if not candidate: raise ValueError('Select a reviewed flag image.')
        # Old-country flag candidates must never be applied after changing the country.
        if art.norm(official_review.badge_country(candidate.get('value',''))) != art.norm(country):
            raise ValueError('This badge belongs to an earlier country or region selection.')
        if art.norm(country)=='asia' and not (decisions.get('country',{}).get('state')=='manual'
                and official_review.approved_choice(next((x for x in queue_supplier() if x.get('id')==identifier),None),'country','Asia')
                and candidate.get('regionalBadge') is True
                and candidate.get('value')=='Asia regional badge'):
            raise ValueError('Asia is a competition region, not a national flag; explicitly approve the official region first.')
        image=FLAGS/(candidate_id+'.png')
        if not image.is_file():raise ValueError('Flag image is unavailable.')
        # Explicit approval may replace an existing flag; the established logo
        # library handles its own backup and cache-busting URL.
        previous=decisions.get('countryLogo',{})
        if not (previous.get('candidateId')==candidate_id and art.norm(country) in country_logos()):
            save_logo(country,'data:image/png;base64,'+base64.b64encode(image.read_bytes()).decode('ascii'))
        decisions['countryLogo']={'state':'manual','value':country,'candidateId':candidate_id,'approvedAt':dt.datetime.now(dt.timezone.utc).isoformat()}
        c.execute('UPDATE fixture_checks SET decisions_json=? WHERE id=?',(json.dumps(decisions),identifier))
        c.commit()
    return {'ok':True,'country':country}

# Phase12D: refresh a missing/changed national flag WITHOUT a costly full
# fixture verification scan. Only an explicitly selected or independently
# verified country is eligible. Never grant a fixture vote or replace a flag.
def start_flag_refresh(identifier,queue_supplier,country_logos=None):
    if not isinstance(identifier,str) or not re.fullmatch(r'sr_[a-f0-9]{24}',identifier):
        raise ValueError('Invalid queue fixture ID.')
    if identifier not in {str(r.get('id')) for r in queue_supplier()}:
        raise ValueError('Fixture no longer pending.')
    with LOCK,closing(get_conn()) as c:
        row=c.execute('SELECT values_json,decisions_json FROM fixture_checks WHERE id=?',(identifier,)).fetchone()
    if not row:raise ValueError('Verify the fixture before searching for flags.')
    fields=json.loads(row['values_json'])
    decisions=json.loads(row['decisions_json'])
    manual=decisions.get('country') or {}
    verified=_effective_country(identifier,fields,decisions)
    country=(clean(manual.get('value')) if manual.get('state')=='manual'
             else clean(verified.get('value')) if verified.get('state')=='verified' else '')
    if not country:raise ValueError('Approve the country before searching for a flag.')
    if WORKER.locked():return {'started':False,'running':True,'reason':'fixture_scan_busy'}
    if not FLAG_WORKER.acquire(False):return {'started':False,'running':True,'reason':'flag_search_busy'}
    def task():
        try:
            try:found,message=flag_candidates(country)
            except Exception as exc:
                found=[];message='Flag lookup unavailable: '+type(exc).__name__
            with LOCK,closing(get_conn()) as c:
                row=c.execute('SELECT values_json,decisions_json FROM fixture_checks WHERE id=?',(identifier,)).fetchone()
                if not row:return
                fresh=json.loads(row['values_json'])
                chosen=json.loads(row['decisions_json'])
                curr=chosen.get('country') or {}
                effective=_effective_country(identifier,fresh,chosen)
                current_country=(clean(curr.get('value')) if curr.get('state')=='manual'
                    else clean(effective.get('value')) if effective.get('state')=='verified' else '')
                if art.norm(current_country)!=art.norm(country):return
                # Never keep a previous country's flag choices after a change.
                previous=(fresh.get('countryLogo') or {}).get('evidence') or []
                choices=[x for x in previous if isinstance(x,dict)
                         and art.norm(official_review.badge_country(x.get('value','')))==art.norm(country)]
                ids={x.get('id') for x in choices}
                for item in found:
                    if item.get('id') not in ids:
                        choices.append(item)
                        ids.add(item.get('id'))
                approved_library=country_logos() if country_logos else {}
                saved=art.norm(country) in approved_library
                fresh['countryLogo']={'state':'verified' if saved else 'review',
                    'value':country if saved else '',
                    'evidence':choices,
                    'message':('Saved flag retained; '+message if saved else
                        'Approve a reviewed flag to save it. '+message)}
                c.execute('UPDATE fixture_checks SET values_json=? WHERE id=?',
                          (json.dumps(fresh),identifier))
                c.commit()
        finally:
            FLAG_WORKER.release()
    try:
        threading.Thread(target=task,daemon=True,name='CountryFlagOnlyRecovery').start()
    except Exception:
        FLAG_WORKER.release()
        raise
    return {'started':True,'running':True,'country':country}

def _effective_country(fixture,fields,decisions):
    """Return the effective country field; raw votes/decisions remain unchanged."""
    country=fields.get('country') or {}
    proof=official_review.domestic_country_proof(fixture,fields,decisions)
    if not proof:return country
    return {**country,'state':'verified','value':proof['country'],
            'verificationBasis':'audited_domestic_competition','countryProof':proof,
            'message':'Country derived from audited official domestic fixture, confirmed league and kickoff; no provider votes added.'}


def _current_country_flag_status(fields, decisions, saved_flags):
    """Read-only reconciliation of confirmed country and shared saved flag."""
    manual=(decisions or {}).get('country') or {}
    auto=fields.get('country') or {}
    country=clean(manual.get('value')) if manual.get('state')=='manual' else clean(auto.get('value')) if auto.get('state')=='verified' else ''
    if not country:return
    entry=fields.get('countryLogo') or {}
    if not isinstance(entry,dict):entry={}
    choices=[x for x in entry.get('evidence',[]) if isinstance(x,dict)
             and art.norm(official_review.badge_country(x.get('value','')))==art.norm(country)]
    if art.norm(country) in saved_flags:
        fields['countryLogo']={**entry,'state':'verified','value':country,'evidence':choices,
            'message':'Existing saved country flag reused; no artwork changed.'}
    else:
        message=str(entry.get('message') or '')
        prefix='Country is provisional; approve it before saving a flag. '
        if message.startswith(prefix):message=message[len(prefix):]
        if not choices or entry.get('state')=='verified' or message.startswith(('Saved flag','Reusing saved flag','Existing saved country flag')):
            message='No saved flag for the confirmed country. Review a matching flag candidate.'
        fields['countryLogo']={**entry,'state':'review','value':'','evidence':choices,
            'message':message or 'Country confirmed; flag artwork still requires verification.'}


def status(country_logos=None):
    with LOCK, closing(get_conn()) as c:
        rows=c.execute('SELECT * FROM fixture_checks ORDER BY checked_at DESC LIMIT 250').fetchall()
    entries={r['id']:{'checkedAt':r['checked_at'],'fields':json.loads(r['values_json']),
                      'decisions':json.loads(r['decisions_json']),
                      'errors':json.loads(r['errors_json'])} for r in rows}
    # Legacy saved reviews can display all 16 provider statuses immediately,
    # without altering stored evidence, votes, decisions or database rows.
    added=added_sources.configured_status()
    saved_flags=country_logos() if country_logos else {}
    for item_id,row in entries.items():
        fields=row['fields']
        health=fields.get('sourceHealth') or {}
        merged=unified.source_health_snapshot(extended_status=added)['sources']
        merged.update(health.get('sources') or {})
        fields['sourceHealth']={'version':2,'sources':merged}
        # Only manual review options; no change to automatic votes, country or approved values.
        official_review.enrich(fields,item_id)
        effective=_effective_country(item_id,fields,row['decisions'])
        if effective.get('verificationBasis')=='audited_domestic_competition':
            fields['country']=effective
            meta=fields.get('officialReview') or {}
            meta.update(countryNeedsSeparateDecision=False,countryProof=effective['countryProof'],
                        notes='Country derived from audited domestic competition; official research adds zero provider votes.')
        if country_logos is not None:
            _current_country_flag_status(fields,row['decisions'],saved_flags)
        core=((fields.get('providerHealth') or {}).get('core') or {})
        fields['providerSummary']={
            'registered':len(unified.ALL_SOURCES),
            'retained':len(source_policy.RETAINED),
            'activeResearch':len(source_policy.ACTIVE_RESEARCH),
            'supporting':len(source_policy.SUPPORTING),
            'disabled':len(source_policy.DISABLED),
            'voteEligible':sum(bool(v) for v in unified.AUTO_VOTE_CAPABILITIES.values()),
            'coreAttempted':sum(bool((core.get(k) or {}).get('attempted')) for k in SOURCES),
            'coreMatched':sum((core.get(k) or {}).get('status')=='matched' for k in SOURCES),
            'independentVotes':max((int((fields.get(k) or {}).get('votes') or 0)
                                   for k in ('kickoff','country','league')),default=0),
        }
    with LOCK: progress=dict(PROGRESS)
    return {'ok':True,'items':entries,'running':WORKER.locked(),
            'flagRunning':FLAG_WORKER.locked(),'progress':progress,
            'sources':{'API-Football':'enabled (free quota)' if art.api_football_key() else 'requires FA_API_FOOTBALL_KEY (free)',
                       'TheSportsDB':'enabled','ESPN':'selected leagues only',
                       'football-data.org':'enabled (limited leagues)' if os.environ.get('FA_FOOTBALL_DATA_TOKEN') else 'requires FA_FOOTBALL_DATA_TOKEN (free)',
                       'OpenLigaDB':'disabled (archived; no live fixture requests)',
                       'OpenFootball':'enabled (schedule data; kickoff may be absent)',
                       'Wikidata/Wikimedia':'enabled (team artwork via existing crest scanner)',
                       'Tavily':'enabled (free search allowance)' if os.environ.get('FA_TAVILY_API_KEY') else 'requires FA_TAVILY_API_KEY (optional free key)',
                       'Official web recovery':'enabled · manual evidence only' if os.environ.get('FA_BRAVE_SEARCH_KEY') else 'requires FA_BRAVE_SEARCH_KEY (optional; no changes to other providers)',
                       **{name:(('requires '+added_sources.KEYS[name])
                                if info['status']=='key_required' else
                                (info['status']+' · '+info['reason']))
                          for name,info in added.items()}}}


def scan(queue_supplier, country_logos=None, save_country_logo=None,force=False):
    if FLAG_WORKER.locked():return {'started':False,'running':True}
    if not WORKER.acquire(False):return {'started':False,'running':True}
    def task():
        try:
            queue=queue_supplier()
            with LOCK:PROGRESS.update(checked=0,total=len(queue),current='',finishedAt='')
            processed=0
            for fixture in queue:
                if processed>=MAX_PER_SCAN:break
                id=fixture['id']
                with LOCK, closing(get_conn()) as c:
                    old=c.execute('SELECT checked_at, decisions_json, values_json FROM fixture_checks WHERE id=?',(id,)).fetchone()
                if not force and not _fixture_retry_due(old,time.time()):continue
                with LOCK:PROGRESS['current']=fixture['home']+' vs '+fixture['away']
                # FA_PROVIDER_ROUTING_V1: recovered manual identity guides
                # eligibility but never counts as a new provider vote.
                old_decisions = json.loads(old['decisions_json']) if old else {}
                fields,errors,provider_health=evaluate(
                    fixture,approved_identity=old_decisions,include_health=True)
                _retain_api_date_deferral(old,provider_health,time.time())
                fields['providerHealth'] = provider_health
                # FA_ENRICHMENT_OBSERVABILITY_V4: never hide fallback failure.
                recovery_note='Fallback not attempted'
                recovery_counts={}
                suggested={}
                # Recognized competition -> country is a REVIEW suggestion only.
                # It is not a new source vote and never overrides approved data.
                if fields['country']['state']!='verified' and not fields['country']['evidence']:
                    leagues={league_key(x.get('value')) for x in fields['league']['evidence'] if x.get('value')}
                    mapped={country for country,league in KNOWN_LEAGUES.values() if league_key(league) in leagues}
                    if len(leagues)==1 and len(mapped)==1:
                        country=next(iter(mapped))
                        fields['country']['evidence'].append({
                            'source':'Local competition-country catalog (manual)',
                            'value':country,'reference':'','recovery':True})
                        fields['country']['message']+=' · Country suggested from recognized competition for manual review'
                # FA_AUTOMATIC_MISSING_INFORMATION_V1: after four-source voting,
                # search ONLY missing fields. Supplementary web results are
                # evidence for manual approval, never extra quorum votes.
                old_decisions=json.loads(old['decisions_json']) if old else {}
                try:
                    recovered,diagnostic=web_recovery.recover(
                        fixture,fields,old_decisions,force=force)
                    for field,candidates in recovered.items():
                        if field not in ('kickoff','country','league'):continue
                        original=fields[field]['evidence']
                        seen={(x.get('source'),x.get('value')) for x in original}
                        for candidate in candidates:
                            if (candidate.get('source'),candidate.get('value')) not in seen:
                                original.append(candidate)
                        fields[field]['recoveryCount']=len(candidates)
                        fields[field]['message'] += ' · '+str(len(candidates))+' official web suggestion(s) available for manual approval'
                    if diagnostic and (diagnostic.startswith('Search provider') or diagnostic.startswith('Official web lookup') or diagnostic.startswith('No matching')):
                        errors['Official web recovery']=diagnostic
                except Exception as exc:
                    errors['Official web recovery']='Lookup unavailable ('+type(exc).__name__+').'
                # FA_FOUR_FREE_RECOVERY_V1: optional fallback suggestions only.
                # They never contribute to the existing four-provider vote count,
                # never overwrite approvals and are not a match-import prerequisite.
                old_decisions_for_recovery=json.loads(old['decisions_json']) if old else {}
                old_fields_for_recovery=json.loads(old['values_json']) if old else {}
                try:
                    suggested, recovery_note=free_recovery.recover(
                        fixture,fields,old_decisions_for_recovery,force=force)
                    recovery_counts={key:len(value) for key,value in suggested.items()}
                    for key in ('kickoff','country','league'):
                        if (old_decisions_for_recovery.get(key) or {}).get('state')=='manual':
                            # Retain evidence for repeat reapprovals; never change value.
                            pass
                        existing=fields[key].setdefault('evidence',[])
                        old_recovery=[e for e in (old_fields_for_recovery.get(key) or {}).get('evidence',[])
                                      if e.get('recovery') is True and free_recovery.reference_date_compatible(fixture,e.get('reference',''))]
                        # Preserve exact first-party research reviewed in Phase9D
                        # across rescans; neither the old research nor future
                        # new-provider matches can cast an automatic vote.
                        old_official=added_sources.preserved_first_party_choices(
                            fixture,old_fields_for_recovery,key)
                        additions=old_recovery+old_official+suggested.get(key,[])
                        known={(e.get('source'),e.get('value')) for e in existing}
                        added=0
                        for candidate in additions:
                            value=str(candidate.get('value',''))
                            if (candidate.get('source'),value) not in known:
                                existing.append(candidate)
                                known.add((candidate.get('source'),value))
                                added+=1
                        if added:
                            fields[key]['message']+=' · '+str(added)+' supplementary source choice(s) available for manual approval'
                except Exception as exc:
                    # A fallback outage cannot block the importer, but it must
                    # be observable; do not disclose keys or URL query secrets.
                    recovery_note='Fallback failed ('+type(exc).__name__+')'
                    errors['Free recovery']='Fallback '+type(exc).__name__
                # FA_UNIFIED_16_REVIEW_V1: bounded optional API-Ninjas and
                # Bzzoiro research joins the SAME evidence fields. Every added
                # source remains human review ONLY; it never enters 'records',
                # 'vote' or any 3-source quorum calculation.
                extra_status=added_sources.configured_status()
                try:
                    extra_suggested,extra_status=added_sources.recover(
                        fixture,fields,old_decisions_for_recovery)
                    for key,choices in extra_suggested.items():
                        if key not in ('kickoff','country','league'):continue
                        original=fields[key].setdefault('evidence',[])
                        known={(e.get('source'),e.get('value')) for e in original}
                        new_count=0
                        for candidate in choices:
                            label=(candidate.get('source'),candidate.get('value'))
                            if label not in known and candidate.get('identityReview'):
                                original.append(candidate)
                                known.add(label)
                                new_count+=1
                        if new_count:
                            recovery_counts[key]=recovery_counts.get(key,0)+new_count
                            fields[key]['message']+=' · '+str(new_count)+' new provider research choice(s), manual review only'
                except Exception as exc:
                    errors['Expanded source review']='Unavailable ('+type(exc).__name__+').'
                fields['sourceHealth'] = unified.source_health_snapshot(
                    provider_health, suggested, extended_status=extra_status)
                official_review.enrich(fields,fixture)  # source-backed manual choices only
                fields['recoveryInfo']={
                    'diagnostic':str(recovery_note)[:850],
                    'candidateCounts':recovery_counts,
                    'checkedAt':dt.datetime.now(dt.timezone.utc).isoformat(),
                    'automaticVotes':0,
                }
                # Flag evidence remains independent of the fixture country vote.
                # Never claim logo consensus based on country-name consensus.
                known=(country_logos() if country_logos else {})
                nation=fields['country'].get('value')
                old_decisions=json.loads(old['decisions_json']) if old else {}
                nation=old_decisions.get('country',{}).get('value') or nation
                # A unique provisional source-backed country may enable a flag
                # CHOICE before the country is confirmed. It is not permission
                # to save a flag or mark the country as verified.
                provisional_nation=False
                if not nation:
                    countries={clean(e.get('value')) for e in fields['country'].get('evidence',[])
                               if clean(e.get('value'))}
                    if len({art.norm(x) for x in countries})==1 and countries:
                        nation=sorted(countries)[0]
                        provisional_nation=True
                if nation and art.norm(nation) in known:
                    # Reapproval: the existing shared flag must remain unchanged on a scan.
                    # Refresh the available choices only when the user explicitly scans,
                    # while retaining earlier reviewed images if providers are unavailable.
                    previous_fields=json.loads(old['values_json']) if old else {}
                    previous=previous_fields.get('countryLogo',{})
                    retained=[x for x in previous.get('evidence',[])
                              if art.norm(official_review.badge_country(x.get('value','')))==art.norm(nation)]
                    note='Reusing saved flag; previous review options remain available'
                    if force:
                        try:
                            fresh, report=flag_candidates(nation)
                            known_ids={x.get('id') for x in retained}
                            retained += [x for x in fresh if x.get('id') not in known_ids]
                            note='Saved flag retained. '+report+'; select another reviewed image to change it.'
                        except Exception as exc:
                            note='Saved flag retained. Refresh failed: '+type(exc).__name__
                    fields['countryLogo']={'state':'review' if provisional_nation else 'verified',
                        'value':'' if provisional_nation else nation,'evidence':retained,
                        'message':('Saved flag exists; approve the suggested country first' if provisional_nation else note)}
                elif nation:
                    try:
                        items,message=flag_candidates(nation)
                    except Exception as exc:
                        items=[]
                        message='Flag service unavailable ('+type(exc).__name__+'); fixture details retained'
                    all_three=len(items)>=3 and re.match(r'^[34] of [34] flag-image services agree',message) is not None
                    if all_three and save_country_logo and not provisional_nation:
                        try:
                            preview=FLAGS/(items[0]['id']+'.png')
                            save_country_logo(nation,'data:image/png;base64,'+base64.b64encode(preview.read_bytes()).decode('ascii'))
                        except Exception as exc:
                            all_three=False;message='Flag saving needs review: '+type(exc).__name__
                    fields['countryLogo']={'state':'verified' if all_three and not provisional_nation else 'review',
                        'value':nation if all_three and not provisional_nation else '',
                        'evidence':items,
                        'message':('Country is provisional; approve it before saving a flag. '+message)
                        if provisional_nation else message}
                else:
                    fields['countryLogo']={'state':'review','value':'','evidence':[],
                                           'message':'Confirm country before verifying its flag'}
                # Keep manually approved field decisions, never discard them on re-scan.
                decisions=json.loads(old['decisions_json']) if old else {}
                with LOCK, closing(get_conn()) as c:
                    c.execute('INSERT INTO fixture_checks(id,checked_at,values_json,evidence_json,decisions_json,errors_json) VALUES(?,?,?,?,?,?) '
                              'ON CONFLICT(id) DO UPDATE SET checked_at=excluded.checked_at,values_json=excluded.values_json,'
                              'evidence_json=excluded.evidence_json,errors_json=excluded.errors_json',
                              (id,int(time.time()),json.dumps(fields),json.dumps([]),json.dumps(decisions),json.dumps(errors)))
                    c.commit()
                processed+=1
                with LOCK:PROGRESS['checked']=processed
                time.sleep(.25)
        finally:
            with LOCK:PROGRESS.update(current='',finishedAt=dt.datetime.now(dt.timezone.utc).isoformat())
            WORKER.release()
    try:
        threading.Thread(target=task,daemon=True,name='FixtureVerification').start()
    except Exception:
        WORKER.release();raise
    return {'started':True,'running':True}


def approve(identifier,field,value,queue_supplier):
    if not isinstance(identifier,str) or not re.fullmatch(r'sr_[a-f0-9]{24}',identifier):
        raise ValueError('Invalid fixture ID.')
    if field not in ('kickoff','country','league'):
        raise ValueError('Unknown verification field.')
    value=clean(value)
    if not value or len(value)>120:raise ValueError('Choose a valid value.')
    if field=='kickoff':
        if not re.fullmatch(r'\d{4}-\d\d-\d\d \d\d:\d\d',value):
            raise ValueError('Enter kickoff as YYYY-MM-DD HH:MM UTC.')
        dt.datetime.strptime(value,'%Y-%m-%d %H:%M')
    fixture=next((r for r in queue_supplier() if r.get('id')==identifier),None)
    if fixture is None:
        raise ValueError('Fixture is no longer in the review queue.')
    with LOCK, closing(get_conn()) as c:
        row=c.execute('SELECT decisions_json, values_json FROM fixture_checks WHERE id=?',(identifier,)).fetchone()
        if not row:raise ValueError('Scan this fixture first.')
        fields=json.loads(row['values_json'])
        choices={clean(item.get('value')) for item in fields.get(field,{}).get('evidence',[])}
        if value not in choices and not official_review.approved_choice(fixture,field,value):
            raise ValueError('Select a value actually reported for this fixture by an independent source.')
        decisions=json.loads(row['decisions_json'])
        # A country change invalidates a prior country-specific flag approval.
        if field=='country':
            old_country=decisions.get('country',{}).get('value') or fields.get('country',{}).get('value')
            if art.norm(old_country)!=art.norm(value):decisions.pop('countryLogo',None)
        decisions[field]={'state':'manual','value':value,'approvedAt':dt.datetime.now(dt.timezone.utc).isoformat()}
        c.execute('UPDATE fixture_checks SET decisions_json=? WHERE id=?',(json.dumps(decisions),identifier))
        c.commit()
    return {'ok':True,'id':identifier,'field':field,'value':value}


# FA_CARD_DROPDOWN_V2: source-backed manual approvals stay separate from final import.
def confirmed_for_import(identifier, queue_supplier, country_logos, team_logos):
    """Enforce verifications on server, not merely in a disabled HTML button."""
    if not isinstance(identifier,str) or not re.fullmatch(r'sr_[a-f0-9]{24}',identifier):
        raise ValueError('Invalid fixture ID.')
    rows={r['id']:r for r in queue_supplier()}
    fixture=rows.get(identifier)
    if not fixture:raise ValueError('Fixture is no longer pending.')
    with LOCK,closing(get_conn()) as c:
        row=c.execute('SELECT values_json,decisions_json FROM fixture_checks WHERE id=?',(identifier,)).fetchone()
    if not row:raise ValueError('Verify fixture details before importing.')
    fields=json.loads(row['values_json'])
    decisions=json.loads(row['decisions_json'])
    fields['country']=_effective_country(fixture,fields,decisions)
    approved={}
    for key in ('kickoff','country','league'):
        manual=decisions.get(key,{})
        auto=fields.get(key,{})
        picked=manual if manual.get('state')=='manual' else auto
        if picked.get('state') not in ('manual','verified') or not clean(picked.get('value')):
            raise ValueError('Approve the '+key+' source result before importing.')
        approved[key]=clean(picked['value'])
    try:
        date_string,time_string=approved['kickoff'].split(' ',1)
        dt.datetime.strptime(approved['kickoff'],'%Y-%m-%d %H:%M')
    except (ValueError,TypeError) as exc:
        raise ValueError('Verified kickoff date/time has an invalid format.') from exc
    # A previously approved country flag in the authoritative library may be reused.
    if art.norm(approved['country']) not in country_logos():
        raise ValueError('Approve the country flag before importing.')
    logos=team_logos()
    for team in (fixture['home'],fixture['away']):
        if art.norm(team) not in logos:
            raise ValueError('Approve the crest for '+team+' before importing.')
    return {'league':approved['league'],'country':approved['country'],
            'kickoff_time':time_string,'match_date':date_string}


# FA_MANUAL_IMPORT_OPTIONAL_VERIFICATION_V1
# Source verification enriches records; it must never be a prerequisite for
# the user's explicit Approve & Import decision.
def metadata_for_manual_import(identifier, queue_supplier):
    """Use independently confirmed values where available, otherwise preserve
    collected metadata (possibly blank). Do not fabricate unverified values.

    The existing importer still enforces a pending candidate, valid match data,
    duplicate checks, reserved IDs, and explicit user approval.
    """
    if not isinstance(identifier,str) or not re.fullmatch(r'sr_[a-f0-9]{24}',identifier):
        raise ValueError('Invalid fixture ID.')
    fixture = next((r for r in queue_supplier() if r.get('id') == identifier), None)
    if fixture is None:
        raise ValueError('Fixture is no longer in the review queue.')

    picks = {}
    if DB.is_file():
        try:
            with LOCK, closing(get_conn()) as c:
                row = c.execute(
                    'SELECT values_json,decisions_json FROM fixture_checks WHERE id=?',
                    (identifier,)).fetchone()
            if row:
                fields = json.loads(row['values_json'])
                decisions = json.loads(row['decisions_json'])
                fields['country']=_effective_country(fixture,fields,decisions)
                for key in ('kickoff','country','league'):
                    manual = decisions.get(key) or {}
                    auto = fields.get(key) or {}
                    selected = manual if manual.get('state') == 'manual' else auto
                    if selected.get('state') in ('verified','manual'):
                        picks[key] = clean(selected.get('value'))
        except (sqlite3.Error, ValueError, TypeError, AttributeError):
            # An unavailable optional verification DB must not block an import.
            picks = {}

    match_date = str(fixture.get('match_date') or '').strip()
    kickoff_time = ''
    chosen_kickoff = picks.get('kickoff') or ''
    if re.fullmatch(r'\d{4}-\d\d-\d\d [0-2]\d:[0-5]\d',chosen_kickoff):
        try:
            chosen = dt.datetime.strptime(chosen_kickoff,'%Y-%m-%d %H:%M')
            match_date = chosen.strftime('%Y-%m-%d')
            kickoff_time = chosen.strftime('%H:%M')
        except ValueError:
            pass
    # Unverified details are never silently promoted to verified. The existing
    # collector values, where present, can still be imported as ordinary metadata.
    return {
        'match_date':match_date,
        'kickoff_time':kickoff_time,
        'country':str(picks.get('country') or fixture.get('country') or '').strip()[:120],
        'league':str(picks.get('league') or fixture.get('league') or '').strip()[:120],
    }
