"""Optional four-channel missing-fixture recovery, never a verification vote.

Tavily: discovery of permit-readable official SportsEvent JSON-LD (needs free API key).
OpenLigaDB: structured fixtures (mostly German leagues; no personal API key).
OpenFootball: public-domain schedule JSON, typically DATE-only (no invented kickoff).
Wikidata/Wikimedia: club/crest recovery is already handled by sr_logo_discovery;
this module does not duplicate logo uploads or create fictitious logo votes.

No imports, database modifications, automatic approvals, credentials on disk,
web-page scripting, or URL submission from the queue.
"""
from __future__ import annotations
import sr_source_policy as source_policy  # FA_SR_SOURCE_CLEANUP_8_OF_16_20261122

import datetime as dt
import ipaddress
import calendar
import json
import os
import re
import threading
import unicodedata
import time
from html.parser import HTMLParser
from pathlib import Path
from urllib.error import HTTPError
from urllib.parse import urlencode, urlsplit
from urllib.request import Request, build_opener, HTTPRedirectHandler
from urllib.robotparser import RobotFileParser

import sr_logo_discovery as art
import sr_fixture_identity as fixture_identity  # PHASE3_IDENTITY_SAFETY_GUARD
import team_identity_registry as team_registry  # GLOBAL_TEAM_IDENTITY_V1

ROOT = Path(__file__).resolve().parent
CACHE = ROOT / 'soccerrating_free_recovery_cache.json'
LOCK = threading.RLock()
AGENT = 'FootballAnalyticsFreeRecovery/1.0 (local personal fixture research)'
TTL = 15 * 60
NEGATIVE_TTL = 4 * 60  # Do not cache failed searches for eighteen hours
MAX_CACHE = 180
MAX_TAVILY_DAILY = 25
MAX_EXTERNAL_REQUESTS = 100
MAX_FETCH = 3_000_000
_DATA_CACHE = {}
LEAGUES = {
    # Country, league, OpenLigaDB shortcut, OpenFootball file
    'bundesliga': ('Germany', 'Bundesliga', 'bl1', 'de.1'),
    '2 bundesliga': ('Germany', '2. Bundesliga', 'bl2', 'de.2'),
    '3 liga': ('Germany', '3. Liga', 'bl3', 'de.3'),
    'premier league': ('England', 'Premier League', '', 'en.1'),
    'championship': ('England', 'Championship', '', 'en.2'),
    'la liga': ('Spain', 'La Liga', '', 'es.1'),
    'serie a': ('Italy', 'Serie A', '', 'it.1'),
    'ligue 1': ('France', 'Ligue 1', '', 'fr.1'),
}
# Trusted sites are explicitly limited; search results can NEVER direct the
# application to arbitrary private IPs, local hosts, redirects or login URLs.
OFFICIAL_DOMAINS = (
    'jleague.jp','jfa.jp','bundesliga.com','dfb.de','premierleague.com',
    'laliga.com','legaseriea.it','ligue1.com','mlssoccer.com',
    'uefa.com','fifa.com','the-afc.com','efl.com','eredivisie.nl',
    'thefa.com','cbf.com.br','afa.com.ar',
    'chnliga.cz','lfafotbal.cz','fkceskalipa.cz','ligaportugal.pt',
    'seriec.com','novarafootballclub.it','milanorange1952.com','barletta1922.com','inter.it',
    '1liga.org','pzpn.pl','chrobry-glogow.pl',
)
ALLOWED_API_HOSTS = {'api.tavily.com','api.openligadb.de','raw.githubusercontent.com'}


def clean(s):
    return re.sub(r'\s+', ' ', str(s or '').strip())[:140]


def league_only(name):
    text=clean(name)
    text=re.sub(r'\s*[-–,|:]\s*(?:round|matchweek|matchday|week|stage)\s*#?\d+.*$', '', text, flags=re.I)
    return text[:100]


def utc_iso(raw):
    try:
        val=dt.datetime.fromisoformat(str(raw).replace('Z','+00:00'))
        if val.tzinfo is None:return ''
        return val.astimezone(dt.timezone.utc).strftime('%Y-%m-%d %H:%M')
    except (TypeError,ValueError):
        return ''


def safe_official_url(url):
    try:
        p=urlsplit(str(url))
        host=(p.hostname or '').rstrip('.').lower()
        return (p.scheme=='https' and p.username is None and p.password is None
                and p.port in (None,443) and len(str(url))<700
                and any(host==d or host.endswith('.'+d) for d in OFFICIAL_DOMAINS))
    except ValueError:
        return False


class _NoRedirect(HTTPRedirectHandler):
    def redirect_request(self,req,fp,code,msg,headers,newurl):
        return None


def _download(url, *, method='GET', body=None, headers=None, maximum=MAX_FETCH):
    p=urlsplit(url)
    if p.scheme!='https' or p.hostname not in ALLOWED_API_HOSTS or p.username or p.password or p.port not in (None,443):
        raise ValueError('Remote API host not approved')
    req=Request(url, data=json.dumps(body).encode('utf-8') if body is not None else None,
                method=method,headers={'User-Agent':AGENT,'Accept':'application/json',**(headers or {})})
    with build_opener(_NoRedirect).open(req,timeout=8) as resp:
        if resp.status!=200:raise ValueError('Provider status not successful')
        if int(resp.headers.get('Content-Length') or 0)>maximum:raise ValueError('Oversized response')
        data=resp.read(maximum+1)
        if len(data)>maximum:raise ValueError('Oversized response')
    return json.loads(data.decode('utf-8'))


def _read_site(url):
    if not safe_official_url(url):raise ValueError('Untrusted official link')
    p=urlsplit(url)
    host=p.hostname
    robot='https://'+host+'/robots.txt'
    try:
        with build_opener(_NoRedirect).open(Request(robot,headers={'User-Agent':AGENT}),timeout=6) as resp:
            if resp.status!=200:raise ValueError('Robots rule unavailable')
            rules=resp.read(110_001)
        if len(rules)>110_000:raise ValueError('Oversized robots')
        rp=RobotFileParser();rp.parse(rules.decode('utf-8','replace').splitlines())
        if not rp.can_fetch(AGENT,url):raise ValueError('Automated access not permitted')
    except (HTTPError,OSError,ValueError) as exc:
        raise ValueError('Cannot confirm robots permission') from exc
    with build_opener(_NoRedirect).open(Request(url,headers={'User-Agent':AGENT,'Accept':'text/html'}),timeout=8) as resp:
        if resp.status!=200 or 'html' not in (resp.headers.get('Content-Type') or '').lower():
            raise ValueError('No readable HTML')
        data=resp.read(250_001)
    if len(data)>250_000:raise ValueError('Page too large')
    return data.decode('utf-8','replace')


class _EventParser(HTMLParser):
    def __init__(self):super().__init__();self.in_script=False;self.content=[];self.scripts=[]
    def handle_starttag(self,tag,attrs):
        if tag=='script' and dict(attrs).get('type','').lower().startswith('application/ld+json'):
            self.in_script=True;self.content=[]
    def handle_data(self,data):
        if self.in_script:self.content.append(data)
    def handle_endtag(self,tag):
        if tag=='script' and self.in_script:
            self.in_script=False;self.scripts.append(''.join(self.content));self.content=[]


def _items(root):
    work=[root];count=0
    while work and count<100:
        o=work.pop(0);count+=1
        if isinstance(o,list):work.extend(o[:30]);continue
        if not isinstance(o,dict):continue
        yield o
        for k in ('@graph','event','mainEntity'):
            if isinstance(o.get(k),(list,dict)):work.append(o[k])


def _name(o):
    return clean(o.get('name','') if isinstance(o,dict) else o)


def official_sportsevent(html, fixture):
    parsed=_EventParser();parsed.feed(html[:250_000])
    found=[];fixture_day=dt.date.fromisoformat(fixture['match_date'])
    for block in parsed.scripts[:20]:
        try:obj=json.loads(block)
        except (ValueError,TypeError):continue
        for event in _items(obj):
            typ=event.get('@type') or []
            if not isinstance(typ,list):typ=[typ]
            if not any(str(t).rsplit('/',1)[-1].lower()=='sportsevent' for t in typ):continue
            kickoff=utc_iso(event.get('startDate'))
            if not kickoff:continue
            home=_name(event.get('homeTeam'));away=_name(event.get('awayTeam'))
            aliases=team_registry.alias_map_for_fixture(
                fixture.get('home'),fixture.get('away'),home,away,
                country=fixture.get('country',''))
            match=fixture_identity.source_fixture(fixture,home,away,kickoff[:10],
                                                   aliases=aliases)
            if match.classification=='reject':continue
            comp=event.get('sportsCompetition') or event.get('superEvent') or {}
            league=league_only(_name(comp))
            country=''
            if isinstance(comp,dict):
                loc=comp.get('location') or {}
                if isinstance(loc,dict):
                    address=loc.get('address') or {}
                    if isinstance(address,dict):country=_name(address.get('addressCountry'))
            result={'kickoff':kickoff,'league':league,'country':country}
            if result not in found:found.append(result)
    return found[0] if len(found)==1 else {}


def _cached_dataset(url, transport):
    """Reuse a whole-league response for all pending fixtures in this process."""
    if transport is not _download:
        return transport(url)  # deterministic injected tests, no global cache leakage
    with LOCK:
        value=_DATA_CACHE.get(url)
        if value and time.time()-value[0]<12*3600:
            return value[1]
    data=transport(url)
    with LOCK:
        if len(_DATA_CACHE)>12:_DATA_CACHE.clear()
        _DATA_CACHE[url]=(time.time(),data)
    return data


def _matching(rows,fixture, *, home_key='home',away_key='away', date_key='date', provider_key='', provider_country='', provider_league=''):
    expected=dt.date.fromisoformat(fixture['match_date'])
    out=[]
    for row in rows:
        if not isinstance(row,dict):continue
        home=clean(row.get(home_key));away=clean(row.get(away_key))
        if provider_key:
            # Avoid expensive identity lookups for irrelevant fixture days.
            try:
                proposed_date=dt.date.fromisoformat(str(row.get(date_key,''))[:10])
            except (TypeError,ValueError):
                continue
            if abs((expected-proposed_date).days)>1:
                continue
            aliases,conflict=team_registry.provider_event_alias_map(
                fixture.get('home'),fixture.get('away'),home,away,
                provider=provider_key,home_id=row.get('home_id'),
                away_id=row.get('away_id'),country=fixture.get('country',''))
            if conflict:continue
        else:
            aliases=team_registry.alias_map_for_fixture(
                fixture.get('home'),fixture.get('away'),home,away,
                country=fixture.get('country',''))
        match=fixture_identity.source_fixture(
            fixture,home,away,str(row.get(date_key,''))[:10],aliases=aliases,
            country=provider_country,league=provider_league)
        if match.classification=='reject':continue
        out.append({**row,'_identity':match.classification,
                    '_identityReason':match.reason})
    # Distinct fixture dates/time identities should not be guessed.
    return out


def competition_for(fixture,fields,decisions):
    candidate=clean((decisions.get('league') or {}).get('value') or (fields.get('league') or {}).get('value'))
    # Candidate hints from a single API are used for ROUTING only, not votes.
    if not candidate:
        for e in (fields.get('league') or {}).get('evidence',[]):
            name=league_only(e.get('value'))
            if name:candidate=name;break
    candidate=art.ident(candidate)
    aliases={'german bundesliga':'bundesliga','english premier league':'premier league',
             'italian serie a':'serie a','spanish la liga':'la liga',
             'french ligue 1':'ligue 1','bundesliga 2':'2 bundesliga'}
    comp=LEAGUES.get(aliases.get(candidate,candidate))
    if not comp:return None
    # FA_COUNTRY_SCOPED_RECOVERY_ROUTE_V1: An unreviewed league excerpt must
    # never supply its own country to choose a foreign provider's dataset.
    # A country may be trusted only from the original fixture, an explicit
    # human approval, or an independently verified field. Conflicts abstain.
    # Routing is NOT a source vote or category approval.
    trusted=[clean(fixture.get('country'))]
    country_decision=(decisions.get('country') or {})
    if country_decision.get('state')=='manual':
        trusted.append(clean(country_decision.get('value')))
    country_field=(fields.get('country') or {})
    if country_field.get('state')=='verified':
        trusted.append(clean(country_field.get('value')))
    keys={team_registry._country(value) for value in trusted if value}
    if len(keys)!=1 or team_registry._country(comp[0]) not in keys:
        return None
    return comp


def _openligadb(fixture,comp,transport):
    country,league,shortcut,_=comp
    if not shortcut:return []
    day=dt.date.fromisoformat(fixture['match_date'])
    # OpenLigaDB uses the YEAR IN WHICH THE SEASON BEGINS, e.g. 2026 for 2026/27.
    season=day.year if day.month>=7 else day.year-1
    url=f'https://api.openligadb.de/getmatchdata/{shortcut}/{season}'
    raw=_cached_dataset(url,transport)
    if not isinstance(raw,list):return []
    rows=[]
    for r in raw[:1200]:
        if not isinstance(r,dict):continue
        teams=(r.get('team1') or {},r.get('team2') or {})
        utc_raw=str(r.get('matchDateTimeUTC') or '')
        # This API field is explicitly documented/named UTC, unlike local
        # matchDateTime; make that convention explicit only for this field.
        if re.fullmatch(r'\d{4}-\d\d-\d\dT\d\d:\d\d(?::\d\d)?(?:\.\d+)?',utc_raw):
            utc_raw+='+00:00'
        rows.append({'home':clean(teams[0].get('teamName')),'away':clean(teams[1].get('teamName')),
                     'date':clean(r.get('matchDateTimeUTC') or r.get('matchDateTime')),
                     'utc':utc_iso(utc_raw), 'match_id':r.get('matchID'),
                     'home_id':teams[0].get('teamId'),'away_id':teams[1].get('teamId')})
    matches=_matching(rows,fixture,provider_key='openligadb',provider_country=country,provider_league=league)
    if len(matches)!=1:return []
    match=matches[0]
    # Do not infer a UTC offset for matches where provider omitted it.
    result={'country':country,'league':league}
    if match['utc']:result['kickoff']=match['utc']
    reference=f'https://www.openligadb.de/MatchDetails/{match["match_id"]}' if match['match_id'] is not None else 'https://www.openligadb.de/'
    return [{'source':'OpenLigaDB','reference':reference,'values':result,
             'identityReview':match['_identity']=='review',
             'identityReason':match['_identityReason'],
             'sourceHome':match['home'],'sourceAway':match['away']}]


def _openfootball(fixture,comp,transport):
    country,league,_,code=comp
    day=dt.date.fromisoformat(fixture['match_date'])
    season=f'{day.year if day.month>=7 else day.year-1}-{(day.year+1 if day.month>=7 else day.year)%100:02d}'
    url=f'https://raw.githubusercontent.com/openfootball/football.json/master/{season}/{code}.json'
    data=_cached_dataset(url,transport)
    if not isinstance(data,dict) or not isinstance(data.get('matches'),list):return []
    rows=[]
    for m in data['matches'][:1600]:
        if isinstance(m,dict):
            rows.append({'home':m.get('team1'),'away':m.get('team2'),'date':m.get('date')})
    found=_matching(rows,fixture)
    if len(found)!=1:return []
    # OpenFootball fixtures generally contain date only, so NEVER invent 00:00 GMT.
    match=found[0]
    return [{'source':'OpenFootball','reference':url,'values':{'country':country,'league':league},
             'identityReview':match['_identity']=='review',
             'identityReason':match['_identityReason'],
             'sourceHome':match['home'],'sourceAway':match['away']}]


# FA_TAVILY_SEARCH_EVIDENCE_V2
# The earlier implementation threw away every search result without permitted
# official SportsEvent JSON-LD. This additional, strictly REVIEW-ONLY path can
# recover directly supported details from Tavily's indexed title and snippet.
# No third-party site is fetched, no search result becomes a verification vote,
# and a matching club pair + date are mandatory for every snippet suggestion.
def _safe_reference(url):
    try:
        parsed=urlsplit(str(url))
        host=(parsed.hostname or '').rstrip('.').lower()
        if parsed.scheme!='https' or parsed.username or parsed.password or parsed.port not in (None,443):return False
        if not host or len(host)>245 or len(str(url))>700 or '.' not in host:return False
        if any(c not in 'abcdefghijklmnopqrstuvwxyz0123456789-.' for c in host):return False
        if host.startswith('localhost.') or host.endswith(('.local','.internal','.test','.invalid')):return False
        try:ipaddress.ip_address(host);return False
        except ValueError:pass
        return True
    except (ValueError,TypeError):return False


# FA_REAL_WORLD_CLUB_ALIASES_V3. These are explicit, football-specific name
# equivalents, NOT fuzzy matching or automatic verification votes. The matching
# match date is still mandatory before a web snippet becomes a manual suggestion.
_CLUB_ALIASES = {
    'osc lille': ('losc lille', 'lille osc', 'lille olympique sporting club'),
    'losc lille': ('osc lille', 'lille osc', 'lille olympique sporting club'),
    'lille osc': ('osc lille', 'losc lille', 'lille olympique sporting club'),
    'olympique lyon': ('olympique lyonnais', 'olympique lyonnais lyon'),
    'olympique lyonnais': ('olympique lyon',),
}


def _team_mentioned(team, text):
    """Conservative variant-aware club identity recognition for WEB suggestions.

    Never equate generic City/United clubs, youth, reserves or women with a
    senior club. Names with distinctive words can match even if prefixed by
    FC/SC/TSG, but a fixture still needs both teams and an exact date.
    """
    key=art.ident(team)
    hay=' '+art.ident(text)+' '
    if not key or len(key)<4:return False
    approved_aliases=tuple(_CLUB_ALIASES.get(key,()))+team_registry.verified_names(team)
    names=[key]+[art.ident(a) for a in approved_aliases if art.ident(a)]
    if any(' '+alias+' ' in hay for alias in names):
        return fixture_identity.web_mention_category_safe(team,text,aliases=approved_aliases)
    # Expand only leading administrative club prefixes. Do not fuzzy-match city,
    # 'United', 'Slavia', reserve teams or the home/away result itself.
    without_prefix=re.sub(r'^(?:fk|sk|fc|afk|ac|sc)\s+', '',key)
    if without_prefix!=key and len(without_prefix.split())>=2 and len(without_prefix)>=10:
        if ' '+without_prefix+' ' in hay:
            return fixture_identity.web_mention_category_safe(team,text,aliases=_CLUB_ALIASES.get(key,()))
    tokens=[t for t in key.split() if len(t)>=5 and
            t not in {'united','city','sporting','athletic','football',
                      'rangers','rovers','college','olympique','sport','club',
                      'real','inter','nacional','universidad','reserve',
                      'manchester','sheffield','nottingham','bristol',
                      'birmingham','oxford','cambridge','madrid',
                      'women','junior','saint','stade','town','county'}]
    # For e.g. 'TSG Hoffenheim' or 'FC Barcelona', one exceptional long and
    # distinctive token is enough *only* when no other team shares it.
    if len(tokens)==1 and len(tokens[0])>=7 and ' '+tokens[0]+' ' in hay:
        return fixture_identity.web_mention_category_safe(team,text,aliases=_CLUB_ALIASES.get(key,()))
    return False


def _fixture_date_mentioned(match_date,text):
    try:date=dt.date.fromisoformat(match_date)
    except ValueError:return False
    text=str(text)
    if re.search(r'\b'+re.escape(date.isoformat())+r'\b',text):return True
    if re.search(r'\b'+str(date.year)+r'[-/.]0?'+str(date.month)+r'[-/.]0?'+str(date.day)+r'\b',text):return True
    if re.search(r'\b0?'+str(date.day)+r'[-/.]0?'+str(date.month)+r'[-/.]'+str(date.year)+r'\b',text):return True
    # Full-year dates in commonly published fixture languages. Reject day/month
    # without a year; the same teams may meet several times in different years.
    months=(
        ('janvier','février','mars','avril','mai','juin','juillet','août','septembre','octobre','novembre','décembre'),
        ('enero','febrero','marzo','abril','mayo','junio','julio','agosto','septiembre','octubre','noviembre','diciembre'),
        ('janeiro','fevereiro','março','abril','maio','junho','julho','agosto','setembro','outubro','novembro','dezembro'),
        ('januar','februar','märz','april','mai','juni','juli','august','september','oktober','november','dezember'),
        ('gennaio','febbraio','marzo','aprile','maggio','giugno','luglio','agosto','settembre','ottobre','novembre','dicembre'),
        ('stycznia','lutego','marca','kwietnia','maja','czerwca','lipca','sierpnia','września','października','listopada','grudnia'),
    )
    # Czech fixture pages often write '21. 11. 2026' or '21. listopadu 2026'.
    # Require the complete year, never infer it from a 21.11. listing.
    if re.search(r'(?<!\d)0?'+str(date.day)+r'\s*\.\s*0?'+str(date.month)+
                 r'\s*\.\s*'+str(date.year)+r'\b',text):return True
    czech_months=(
        'ledna','unora','brezna','dubna','kvetna','cervna','cervence',
        'srpna','zari','rijna','listopadu','prosince')
    czech_months_accented=(
        'ledna','února','března','dubna','května','června','července',
        'srpna','září','října','listopadu','prosince')
    for month in (czech_months[date.month-1],czech_months_accented[date.month-1]):
        if re.search(r'(?<!\d)0?'+str(date.day)+r'\.?(?:\s+)'+re.escape(month)+
                     r'\s+'+str(date.year)+r'\b',text,re.I):return True
    options={calendar.month_name[date.month],calendar.month_abbr[date.month]}
    options.update(line[date.month-1] for line in months)
    for month in options:
        mm=re.escape(month)
        if re.search(r'\b0?'+str(date.day)+r'(?:st|nd|rd|th|er)?\s*(?:de\s+)?'+mm+r'\.?[,]?\s*(?:de\s+)?'+str(date.year)+r'\b',text,re.I):return True
        if re.search(r'\b'+mm+r'\.?\s*0?'+str(date.day)+r'(?:st|nd|rd|th)?[,]?\s*'+str(date.year)+r'\b',text,re.I):return True
        if re.search(r'\b0?'+str(date.day)+r'\.\s*0?'+str(date.month)+r'\.\s*'+str(date.year)+r'\b',text):return True
    return False



# FA_CZECH_FIXTURE_TIME_V1: Existing Tavily-indexed and robots-permitted
# official-page evidence, not a new provider or an automatic verification vote.
# Require the complete fixture date AND both clubs in the same bounded passage
# before reading the time following that date. This prevents picking a different
# match's kickoff from multi-fixture Czech schedules.
_CZECH_LOCAL_HOSTS = {
    'idnes.cz', 'chnliga.cz', 'lfafotbal.cz', 'fkceskalipa.cz',
}
_CZECH_COMPETITION = re.compile(
    r'\b(?:chance\s+)?n[áa]rodn[íi]\s+liga\b', re.I)


def _czech_date_matches(match_date, text):
    try:
        day=dt.date.fromisoformat(match_date)
    except (TypeError,ValueError):
        return []
    months=(
        'ledna', 'února', 'března', 'dubna', 'května', 'června',
        'července', 'srpna', 'září', 'října', 'listopadu', 'prosince',
    )
    plain=(
        'ledna', 'unora', 'brezna', 'dubna', 'kvetna', 'cervna',
        'cervence', 'srpna', 'zari', 'rijna', 'listopadu', 'prosince',
    )
    numeric=(r'(?<!\d)0?'+str(day.day)+r'\s*[.]\s*0?'+str(day.month)+
             r'\s*[.]\s*'+str(day.year)+r'(?!\d)')
    formats=[numeric, r'(?<!\d)'+re.escape(day.isoformat())+r'(?!\d)']
    for month in {months[day.month-1], plain[day.month-1]}:
        formats.append(r'(?<!\d)0?'+str(day.day)+r'\.?\s+'+
                       re.escape(month)+r'\s+'+str(day.year)+r'(?!\d)')
    seen=set()
    for pat in formats:
        for m in re.finditer(pat,text,re.I):
            if (m.start(),m.end()) not in seen:
                seen.add((m.start(),m.end()))
                yield m


def _czech_offset(date, hour):
    """Prague winter/summer offset; reject non-existent/ambiguous DST hours."""
    last_march=calendar.monthrange(date.year,3)[1]
    last_oct=calendar.monthrange(date.year,10)[1]
    start=dt.date(date.year,3,last_march)-dt.timedelta(
        days=(dt.date(date.year,3,last_march).weekday()+1)%7)
    end=dt.date(date.year,10,last_oct)-dt.timedelta(
        days=(dt.date(date.year,10,last_oct).weekday()+1)%7)
    if date<start or date>end:return 1
    if start<date<end:return 2
    if date==start:return 1 if hour<2 else (2 if hour>=3 else None)
    if date==end:return 2 if hour<2 else (1 if hour>=3 else None)
    return 1


def _czech_fixture_local_times(fixture, text, reference):
    """Read ONLY a local kickoff next to a full dated, matched Czech fixture."""
    try:
        host=(urlsplit(str(reference)).hostname or '').lower().removeprefix('www.')
    except ValueError:
        return set()
    if host not in _CZECH_LOCAL_HOSTS:return set()
    if not _CZECH_COMPETITION.search(text) and host not in ('chnliga.cz','lfafotbal.cz','fkceskalipa.cz'):
        return set()
    day=dt.date.fromisoformat(fixture['match_date'])
    found=set()
    # Preserve original positions, because the date/time adjacency matters.
    dates=list(_czech_date_matches(fixture['match_date'],text))
    for index,date_match in enumerate(dates):
        # Partition multi-fixture lists by their FULL dates. Clubs on the
        # previous fixture's line cannot authenticate the next fixture's time.
        previous_end=dates[index-1].end() if index else 0
        next_start=dates[index+1].start() if index+1<len(dates) else len(text)
        start=max(previous_end,date_match.start()-205)
        end=min(next_start,date_match.end()+90)
        before=text[start:date_match.start()]
        after=text[date_match.end():end]
        before_match=(_team_mentioned(fixture['home'],before) and
                      _team_mentioned(fixture['away'],before))
        after_match=(_team_mentioned(fixture['home'],after) and
                     _team_mentioned(fixture['away'],after))
        if not (before_match or after_match):
            continue
        # Examples: "21.11.2026, 13:30", "21. 11. 2026 13:30",
        # "21. listopadu 2026 od 13.30 hod." and "21.11.2026 (13:30)".
        following=text[date_match.end():date_match.end()+75]
        time_match=re.match(
            r'^\s*[,;\(\[–-]?\s*(?:(?:v|ve|od|v[yý]kop|za[čc][áa]tek)\s*)?'
            r'([01]?\d|2[0-3])([:.])([0-5]\d)\b',following,re.I)
        if not time_match:
            # A clearly labelled kickoff in the same compact fixture entry.
            # Do not use arbitrary clock times from headlines or other matches.
            near=text[max(start,date_match.start()-80):min(end,date_match.end()+90)]
            labelled=re.findall(
                r'\b(?:v[yý]kop|za[čc][áa]tek)\s*(?:v|ve|od)?\s*'
                r'([01]?\d|2[0-3])[:.]([0-5]\d)\b',near,re.I)
            if len(set(labelled))!=1:continue
            hour,minute=map(int,labelled[0])
        else:
            hour,minute=int(time_match.group(1)),int(time_match.group(3))
        offset=_czech_offset(day,hour)
        if offset is None:continue
        local=dt.datetime.combine(day,dt.time(hour,minute),tzinfo=
                                  dt.timezone(dt.timedelta(hours=offset)))
        found.add(local.astimezone(dt.timezone.utc).strftime('%Y-%m-%d %H:%M'))
    return found


class _VisiblePageText(HTMLParser):
    """Plain visible text from an already permitted official HTML page."""
    def __init__(self):
        super().__init__();self.ignored=0;self.parts=[]
    def handle_starttag(self,tag,attrs):
        if tag in ('script','style','noscript','svg'):
            self.ignored+=1
        if not self.ignored and tag in ('p','div','tr','li','h1','h2','h3','h4','br'):
            self.parts.append('\n')
    def handle_endtag(self,tag):
        if tag in ('script','style','noscript','svg') and self.ignored:
            self.ignored-=1
        elif not self.ignored and tag in ('p','div','tr','li','h1','h2','h3','h4'):
            self.parts.append('\n')
    def handle_data(self,data):
        if not self.ignored:self.parts.append(data+' ')


def _official_html_fixture_text(fixture,html,reference):
    """Review-only time from a robots-permitted official page, when matched."""
    if (urlsplit(reference).hostname or '').lower().removeprefix('www.') not in _CZECH_LOCAL_HOSTS:
        return {}
    parser=_VisiblePageText()
    parser.feed(html[:250_000])
    return _indexed_content_event(fixture,'',''.join(parser.parts)[:45_000],reference)


def reference_date_compatible(fixture, reference):
    # Explicit event-date URL paths must not contradict the queue date.
    # Date-free links remain subject to the existing identity checks.
    try:
        path=urlsplit(str(reference or '')).path
        dates=re.findall(r'(?<![0-9])(20[0-9]{2}-[0-9]{2}-[0-9]{2})(?![0-9])',path)
        return not dates or all(dt.date.fromisoformat(x).isoformat()==fixture['match_date'] for x in dates)
    except (ValueError,TypeError,KeyError):
        return False


def _snippet_values(fixture,title,content,reference=""):
    if not reference_date_compatible(fixture,reference):
        return {}
    # Search snippets are not a trustworthy verification source. Candidate
    # values require BOTH club identities and the complete fixture date.
    # Avoid falsely treating youth, women's or reserve fixtures as senior
    # men's matches when a team shares its primary club name.
    if re.search(r'\b(?:women|ladies|femenino|feminines|féminines|lyonnes|reserves?|u[- ]?(?:1[6-9]|2[0-3]))\b',str(title)[:300],re.I):
        return {}
    text=re.sub(r'\s+', ' ', str(title)[:300]+' '+str(content)[:1200]).strip()
    if not (_team_mentioned(fixture['home'],text) and _team_mentioned(fixture['away'],text)
            and _fixture_date_mentioned(fixture['match_date'],text)):
        return {}
    # Reject known youth/women/reserve events even when an indexed body also
    # mentions the senior clubs. Untrusted page text is only an approval option.
    if re.search(r'\b(?:u[- ]?(?:1[6-9]|2[0-3])|under[- ]?(?:1[6-9]|2[0-3])|reserves?|women|ladies|feminino|femenino)\b',text[:330],re.I):
        return {}
    values={}
    # No timezone guess from an arbitrary page. Named UTC/GMT and CET/CEST
    # offsets are unambiguous. A single untz'd time is acceptable ONLY from an
    # official national competition source with a known local timezone.
    times=set()
    explicit_time=False
    for match in re.finditer(r'\b([01]?\d|2[0-3])[:h]([0-5]\d)\s*(UTC|GMT|CET|CEST)\b',text,re.I):
        hour,minute=int(match.group(1)),int(match.group(2))
        zone=match.group(3).upper()
        offset={'UTC':0,'GMT':0,'CET':1,'CEST':2}[zone]
        as_utc=dt.datetime.combine(dt.date.fromisoformat(fixture['match_date']),dt.time(hour,minute),tzinfo=dt.timezone(dt.timedelta(hours=offset))).astimezone(dt.timezone.utc)
        times.add(as_utc.strftime('%Y-%m-%d %H:%M'))
        explicit_time=True
    # Only an official national-competition/club page linked to a recognizable
    # competition can supply an unlabelled local kickoff time. Both Czechia and
    # France follow CET/CEST; ambiguous DST transition times are rejected.
    # Other web sites must explicitly specify GMT, UTC, CET or CEST.
    host=(urlsplit(str(reference)).hostname or '').lower()
    official_french=host in ('ligue1.com','www.ligue1.com') and re.search(r'\bligue\s*1\b',text,re.I)
    # A dated fixture on a Czech-local site may list "13:30" without a
    # timezone label. Treat the time as CET/CEST only after local fixture
    # context is established, and keep the candidate manual-review-only.
    if not explicit_time:
        times.update(_czech_fixture_local_times(fixture,text,reference))
    if not explicit_time and official_french:
        # CET/CEST last-Sunday rules avoid depending on optional Windows
        # timezone databases. An ambiguous DST transition hour is rejected.
        def paris_utc_offset(date,hour):
            last_march=calendar.monthrange(date.year,3)[1]
            last_oct=calendar.monthrange(date.year,10)[1]
            start=dt.date(date.year,3,last_march)-(dt.timedelta(days=(dt.date(date.year,3,last_march).weekday()+1)%7))
            end=dt.date(date.year,10,last_oct)-(dt.timedelta(days=(dt.date(date.year,10,last_oct).weekday()+1)%7))
            if date<start or date>end:return 1
            if start<date<end:return 2
            if date==start:return 1 if hour<2 else (2 if hour>=3 else None)
            if date==end:return 2 if hour<2 else (1 if hour>=3 else None)
            return 1
        local=set()
        for match in re.finditer(r'\b([01]?\d|2[0-3])[:h]([0-5]\d)\b',text,re.I):
            nearby=text[max(0,match.start()-34):min(len(text),match.end()+20)].lower()
            if not re.search(r'\b(?:kickoff|kick-off|coup d.envoi|samedi|dimanche|lundi|mardi|mercredi|jeudi|vendredi|à|at|v[yý]kop|ve|sobota|ned[eě]le|za[čc][áa]tek)\b',nearby,re.I):
                continue
            hour,minute=int(match.group(1)),int(match.group(2))
            offset=paris_utc_offset(dt.date.fromisoformat(fixture['match_date']),hour)
            if offset is None:continue
            as_utc=dt.datetime.combine(dt.date.fromisoformat(fixture['match_date']),dt.time(hour,minute),tzinfo=dt.timezone(dt.timedelta(hours=offset))).astimezone(dt.timezone.utc)
            local.add(as_utc.strftime('%Y-%m-%d %H:%M'))
        if len(local)==1:times.update(local)
    # Accept full ISO datetimes with an explicit offset or Z, but never a bare
    # time without a trustworthy zone; all matches stay review-only.
    iso_times=set()
    for match in re.finditer(r'\b\d{4}-\d\d-\d\d[T ]\d\d:\d\d(?::\d\d)?(?:Z|[+-]\d\d:?\d\d)\b',text):
        when=utc_iso(match.group(0).replace(' ','T'))
        if when and abs((dt.date.fromisoformat(when[:10])-dt.date.fromisoformat(fixture['match_date'])).days)<=1:
            iso_times.add(when)
    # If multiple distinct times appear, abstain rather than guess.
    times.update(iso_times)
    if len(times)==1:values['kickoff']=next(iter(times))
    # A competition name is only a REVIEW suggestion. Avoid assigning a
    # country to ambiguous multi-country names like "Serie A" alone.
    comps=[
        (r'\bj1\s+league\b','J1 League','Japan'),
        (r'\b(?:chance\s+)?n[áa]rodn[íi]\s+liga\b','Chance Národní Liga','Czechia'),
        (r'\bj2\s+league\b','J2 League','Japan'),
        (r'\b(?:2\.?\s+bundesliga|bundesliga\s*2)\b','2. Bundesliga','Germany'),
        # FA_COUNTRY_SPECIFIC_COMPETITIONS_V1: generic names like "Premier
        # League", "Championship" and "Bundesliga" occur in MANY countries.
        # Do not assign England/Germany without explicit origin evidence.
        (r'\b(?:belarus(?:ian)?\s+(?:premier\s+league|vysheyshaya\s+liga|vysshaya\s+liga)|premier\s+league\s+(?:of\s+)?belarus)\b',
         'Belarusian Premier League','Belarus'),
        (r'\b(?:austria|austrian)\s+bundesliga\b|\bbundesliga\s+austria\b',
         'Austrian Bundesliga','Austria'),
        (r'\bgerman\s+bundesliga\b|\bbundesliga\s+germany\b',
         'Bundesliga','Germany'),
        (r'\b(?:english|england)\s+premier\s+league\b|\bpremier\s+league\s+(?:in\s+)?england\b|\bepl\b',
         'Premier League','England'),
        (r'\b(?:efl|english|england)\s+championship\b|\bchampionship\s+england\b',
         'Championship','England'),
        (r'\bla\s+liga\b','La Liga','Spain'),
        (r'\bligue\s+1\b','Ligue 1','France'),
        (r'\bserie\s+a\b','Serie A',''),
        (r'\b(?:major\s+league\s+soccer|mls)\b','MLS','United States'),
        (r'\beredivisie\b','Eredivisie','Netherlands'),
        (r'\bliga\s*portugal\b','Liga Portugal','Portugal'),
        (r'\bprimeira\s*liga\b','Primeira Liga','Portugal'),
        (r'\b(?:betclic\s+(?:1|i)\.?\s+lig[ai]|polish\s+i\s+liga)\b','I Liga','Poland'),
        (r'\bscottish\s+premiership\b','Scottish Premiership','Scotland'),
        (r'\bghan(?:a|aian)\s+premier\s+league\b','Ghana Premier League','Ghana'),
        (r'\bbrazil(?:ian)?\s+(?:s[eé]rie\s+a|brasileir[aã]o)\b','Brasileirão Série A','Brazil'),
        (r'\bargentin(?:a|ean)\s+(?:primera\s+divisi[oó]n|liga\s+profesional)\b','Liga Profesional','Argentina'),
        (r'\bkleague\s*1\b|\bk\s*league\s*1\b','K League 1','South Korea'),
        (r'\ba\s*league\s*men\b','A-League Men','Australia'),
        (r'\bsuper\s+lig\b','Süper Lig','Turkey'),
    ]
    found=[]
    for pattern,league,country in comps:
        if re.search(pattern,text,re.I):
            found.append((league,country))
    # Longest German name wins over the substring "Bundesliga".
    if ('2. Bundesliga','Germany') in found:
        found=[x for x in found if x!=('Bundesliga','Germany')]
    if ('Ghana Premier League','Ghana') in found:
        found=[x for x in found if x!=('Premier League','England')]
    if ('Brasileirão Série A','Brazil') in found:
        found=[x for x in found if x!=('Serie A','')]
    found=set(found)
    if len(found)==1:
        league,country=next(iter(found))
        values['league']=league
        if country:values['country']=country
    return values


# FA_CZECH_APPROVED_IDENTITY_ROUTING_V3: A review queue may have already
# approved the league and country, while a NEW Tavily search response omits
# them. Read those existing approvals solely to choose which official source
# to search for kickoff. Never use an unapproved field or guess a kickoff.
def _approved_czech_route(fields, decisions):
    approved=[]
    for name in ('country','league'):
        decision=(decisions.get(name) or {})
        if decision.get('state')=='manual':
            approved.append(clean(decision.get('value')))
        field=(fields.get(name) or {})
        if field.get('state')=='verified':
            approved.append(clean(field.get('value')))
    return any(art.ident(value) in ('czechia','czech republic','cesko','česko')
               or _CZECH_COMPETITION.search(value) for value in approved)


_DOMESTIC_WEB_PROFILES={
    'Italy':{'hosts':{'seriec.com','novarafootballclub.it','milanorange1952.com'},
             'competition':r'\bserie\s+c\b','league':'Serie C','local_zone':'central_europe',
             'search_words':'Serie C','months':('gennaio','febbraio','marzo','aprile','maggio','giugno','luglio','agosto','settembre','ottobre','novembre','dicembre')},
    'Poland':{'hosts':{'1liga.org','pzpn.pl','chrobry-glogow.pl'},
              'competition':r'\b(?:betclic\s+(?:1|i)\.?\s+lig[ai]|polish\s+i\s+liga|i\s+liga)\b',
              'league':'I Liga','local_zone':'central_europe','search_words':'Betclic 1 Liga',
              'months':('stycznia','lutego','marca','kwietnia','maja','czerwca','lipca','sierpnia','września','października','listopada','grudnia')}
}


def domestic_official_candidate(fixture,title,body,url,*,route=None):
    if not safe_official_url(url) or not reference_date_compatible(fixture,url):return {}
    route=route if route is not None else team_registry.research_pair_route(fixture['home'],fixture['away'])
    profile=_DOMESTIC_WEB_PROFILES.get(route.get('country'))
    host=(urlsplit(url).hostname or '').lower().removeprefix('www.')
    if not profile or host not in profile['hosts']:return {}
    if fixture.get('country') and art.ident(fixture['country'])!=art.ident(route['country']):return {}
    if fixture.get('league') and not re.search(profile['competition'],fixture['league'],re.I):return {}
    if fixture_identity.category(fixture['home']) or fixture_identity.category(fixture['away']):return {}
    day=dt.date.fromisoformat(fixture['match_date'])
    # Explicit ordered matchup, never merely both names somewhere on a page.
    def fold(value):
        return ''.join(c for c in unicodedata.normalize('NFKD',str(value).casefold().replace('ł','l')) if not unicodedata.combining(c))
    home=art.ident(fold(route['home']));away=art.ident(fold(route['away']))
    if min(len(home),len(away))<5:return {}
    sep=r'\s*(?:[-–—]|vs\.?|v\.)\s*'
    pair=re.compile(r'(?<!\w)'+re.escape(home)+r'(?:\s+(?:fc|calcio))?'+sep+re.escape(away)+r'(?!\w)',re.I)
    values=[]
    text=str(title)[:300]+'\n'+str(body)[:24000]
    # Preserve punctuation for fixture/date/time checks.
    for line in re.split(r'\n{2,}|\r\n\r\n',text):
        line=re.sub(r'\s+',' ',line).strip()
        if len(line)>650:continue
        normalized=fold(line)
        if not pair.search(normalized) or not _fixture_date_mentioned(fixture['match_date'],line):continue
        if not re.search(profile['competition'],line,re.I):continue
        if re.search(r'\b(?:under|primavera|giovanili|femminile|women|reserves?|u[- ]?(?:1[5-9]|2[0-3]))\b',line,re.I):continue
        if not all(fixture_identity.web_mention_category_safe(original,line,aliases=(alias,)) for original,alias in ((fixture['home'],route['home']),(fixture['away'],route['away']))):continue
        # Reject passages listing other full dates, and ambiguous times.
        dates=re.findall(r'\b20\d{2}-\d{2}-\d{2}\b',line)
        if any(x!=day.isoformat() for x in dates):continue
        time_pattern=(r'\b(?:godz\.?|godzinie|o)\s*([01]?\d|2[0-3])[:.]([0-5]\d)\b'
                      if route['country']=='Poland' else r'\b(?:ore|alle)\s*([01]?\d|2[0-3])[:.]([0-5]\d)\b')
        times=set(re.findall(time_pattern,line,re.I))
        if len(times)!=1:continue
        hh,mm=map(int,next(iter(times)))
        def last_sunday(month):
            end=dt.date(day.year,month,calendar.monthrange(day.year,month)[1])
            return end-dt.timedelta(days=(end.weekday()+1)%7)
        start,end=last_sunday(3),last_sunday(10)
        if day in (start,end):continue
        off=2 if start<day<end else 1
        utc=dt.datetime.combine(day,dt.time(hh,mm),dt.timezone(dt.timedelta(hours=off))).astimezone(dt.timezone.utc)
        league=profile['league']
        if re.search(r'\bgirone\s+a\b',line,re.I):league+=' - Group A'
        elif re.search(r'\bgirone\s+b\b',line,re.I):league+=' - Group B'
        elif re.search(r'\bgirone\s+c\b',line,re.I):league+=' - Group C'
        v={'country':route['country'],'league':league,'kickoff':utc.strftime('%Y-%m-%d %H:%M')}
        if v not in values:values.append(v)
    return values[0] if len(values)==1 else {}


class _DomesticParagraphs(HTMLParser):
    """Do not combine adjacent matches, navigation or ticket-office hours."""
    def __init__(self):
        super().__init__();self.parts=[];self.current=None;self.ignored=0
    def handle_starttag(self,tag,attrs):
        if tag in ('script','style','noscript'):self.ignored+=1
        if tag=='p' and not self.ignored:self.current=[]
    def handle_endtag(self,tag):
        if tag in ('script','style','noscript'):self.ignored=max(0,self.ignored-1)
        if tag=='p' and self.current is not None:
            self.parts.append(' '.join(self.current));self.current=None
    def handle_data(self,data):
        if self.current is not None and not self.ignored:self.current.append(data)


def domestic_official_html(fixture,html,url,*,route=None):
    parser=_DomesticParagraphs();parser.feed(html[:250000])
    values=[]
    for p in parser.parts[:250]:
        if len(p)>650:continue
        got=domestic_official_candidate(fixture,'',p,url,route=route)
        if got and got not in values:values.append(got)
    return values[0] if len(values)==1 else {}


def _tavily(fixture,transport,site_reader, *, _local_retry=False, _budget_day=None,
            _czech_focus=False, _czech_hint=False):
    key=os.environ.get('FA_TAVILY_API_KEY','').strip()
    if not key:return [],'Tavily: free API key not configured'
    def search_name(team):
        known={'osc lille':'LOSC Lille','olympique lyon':'Olympique Lyonnais'}
        if _local_retry:
            alternates=team_registry.verified_names(team,country=fixture.get('country',''))
            selected=next((name for name in alternates if fixture_identity.normalized(name)!=fixture_identity.normalized(team)),None)
            if selected:return clean(selected)
        return known.get(art.ident(team),clean(team))
    day=dt.date.fromisoformat(fixture['match_date'])
    # FA_INTERNATIONAL_DISCOVERY_V6: Keep the original query first. If it
    # returns no matched evidence, retry once with language-neutral numeric
    # date formatting and no English-only "fixture kickoff league" keywords.
    import sr_official_manual_evidence as official_review
    pair=official_review.reserve_review_route(fixture) or team_registry.research_pair_route(fixture['home'],fixture['away'])
    profile=_DOMESTIC_WEB_PROFILES.get(pair.get('country'))
    if profile and pair.get('reserveReview') is True:
        profile={**profile,'hosts':{'seriec.com','barletta1922.com','inter.it','matchdayprogramme.inter.it'}}
    if fixture.get('country') and art.ident(fixture['country'])!=art.ident(pair.get('country')):profile=None
    if profile and fixture.get('league') and not re.search(profile['competition'],fixture['league'],re.I):profile=None
    if _local_retry:
        # If the first pass found the Czech competition but not kickoff,
        # ask Tavily to index the official league's fixture evidence. This
        # uses the EXISTING provider and never trusts an unlabelled time
        # from a general web domain.
        if _czech_focus:
            query=(f'site:chnliga.cz {search_name(fixture["home"])} '
                   f'{search_name(fixture["away"])} '
                   f'{day.day:02d}.{day.month:02d}.{day.year}')
        elif profile:
            query=(f'{clean(pair["home"])} {clean(pair["away"])} '
                   f'{day.day} {profile["months"][day.month-1]} {day.year} {profile["search_words"]}')
        elif pair and not fixture.get('country') and not fixture.get('league'):
            query=(f'{clean(pair["home"])} {clean(pair["away"])} {clean(pair["country"])} '
                   f'{day.day:02d}.{day.month:02d}.{day.year}')
        else:
            query=(f'{search_name(fixture["home"])} {search_name(fixture["away"])} '
                   f'{day.day:02d}.{day.month:02d}.{day.year}')
    else:
        query=(f'{search_name(fixture["home"])} {search_name(fixture["away"])} '
               f'{day.day} {calendar.month_name[day.month]} {day.year} fixture kickoff league')
    body={'query':query,'search_depth':'basic','max_results':10,'include_answer':False,
          'include_raw_content':'markdown','include_images':False}
    if _local_retry and profile and not _czech_focus:
        body['include_domains']=sorted(profile['hosts'])
    data=transport('https://api.tavily.com/search',method='POST',body=body,
                   headers={'Authorization':'Bearer '+key,'Content-Type':'application/json'})
    if not isinstance(data,dict):return [],'Tavily: invalid search response'
    if data.get('error'):return [],'Tavily: provider reported an error (no key disclosed)'
    items=data.get('results') or []
    seen=set();results=[];matched=0;readable=0;conflicts=0;kickoff_pages=0;official_hits=0;official_failures=0
    for item in sorted(items[:10],key=lambda x: not safe_official_url(x.get('url','')) if isinstance(x,dict) else True):
        if not isinstance(item,dict):continue
        url=item.get('url','')
        if not _safe_reference(url) or not reference_date_compatible(fixture,url):continue
        host=urlsplit(url).hostname
        fixture_data={}
        official_text={};domestic_page={}
        if safe_official_url(url):
            official_hits+=1
            try:
                page=site_reader(url)
                fixture_data=official_sportsevent(page,fixture)
                official_text=_official_html_fixture_text(fixture,page,url)
                if profile:domestic_page=domestic_official_html(fixture,page,url,route=pair)
                if fixture_data or domestic_page:readable+=1
            except Exception:official_failures+=1
        title=item.get('title','')
        excerpt=_snippet_values(fixture,title,item.get('content',''),url)
        if excerpt:matched+=1
        # Search providers may supply full indexed text. Restrict it to a window
        # around the fixture's complete date and two club names; don't parse an
        # entire page containing unrelated fixtures as a single event.
        raw=item.get('raw_content') or ''
        # Existing indexed content, no new network or quota. National profile
        # suggestions are explicitly labelled identity review, never votes.
        domestic=domestic_official_candidate(fixture,title,str(item.get('content') or ''),url,route=pair)
        if not domestic and isinstance(raw,str):
            domestic=domestic_official_candidate(fixture,title,raw,url,route=pair)
        # Never select one of two conflicting fixture times from the same URL.
        if domestic_page:
            if domestic and domestic!=domestic_page:
                conflicts+=1;domestic={}
            else:domestic=domestic_page
        rich={}
        if isinstance(raw,str) and raw:
            rich=_indexed_content_event(fixture,title,raw[:24000],url)
        if rich and excerpt and any(excerpt.get(k) and rich.get(k) and excerpt[k]!=rich[k]
                                    for k in set(rich)&set(excerpt)):
            conflicts+=1
            rich={}  # conflicting matches cannot be silently merged
        # Contradictory times on ONE indexed URL are not independent options.
        # Abstain for kickoff rather than picking official text vs stale snippet.
        source_values=(fixture_data,official_text,excerpt,rich)
        kickoff_values={v['kickoff'] for v in source_values if v.get('kickoff')}
        if len(kickoff_values)>1:
            conflicts+=1
            for values in source_values:values.pop('kickoff',None)
        elif kickoff_values:
            kickoff_pages+=1
        if domestic and kickoff_values and kickoff_values!={domestic.get('kickoff')}:
            domestic.pop('kickoff',None)
        if domestic:
            if domestic.get('kickoff') and not kickoff_values:kickoff_pages+=1
            results.append({'source':'Tavily official domestic · '+host,'reference':url,'values':domestic,
                            'identityReview':True,'identityReason':'registry_country_search_official_fixture_review',
                            'sourceHome':fixture['home'],'sourceAway':fixture['away']})
        for source,values in ((('Tavily official · '+host),fixture_data),
                              (('Tavily official text · '+host),official_text),
                              (('Tavily excerpt · '+host),excerpt),
                              (('Tavily page · '+host),rich)):
            if not values:continue
            # Excerpts from the same host are NOT independent votes.
            record_key=(host,tuple(sorted(values.items())))
            if record_key in seen:continue
            seen.add(record_key)
            results.append({'source':source,'reference':url,'values':values})
    primary=(f'{len(items)} indexed pages; {matched} matched dated fixture excerpts; '
             f'{kickoff_pages} pages with kickoff candidates; '
             f'{readable} official event records; {conflicts} conflicting snippets; '
             f'{official_hits} allowlisted results; {official_failures} official retrieval errors')
    if _local_retry:
        return results,('Tavily (Czech official site): ' if _czech_focus
                        else 'Tavily (official domains): ' if profile else 'Tavily (numeric date): ')+primary
    # FA_CZECH_KICKOFF_RETRY_V2: A country/league candidate is NOT evidence
    # that kickoff has been recovered. The old early return stopped after
    # recovering Czechia/Chance Narodni Liga, leaving kickoff forever empty.
    # A single further query uses the existing Tavily provider and only
    # offers REVIEW-ONLY suggestions when exact club pair + full date match.
    if any(rec.get('values',{}).get('kickoff') for rec in results):
        return results,'Tavily: '+primary
    czech_competition=bool(_czech_hint) or any(
        art.ident(rec.get('values',{}).get('country'))=='czechia' or
        _CZECH_COMPETITION.search(rec.get('values',{}).get('league',''))
        for rec in results)
    # For non-Czech sources retain the original safeguard against wasting the
    # API budget when valid non-kickoff evidence was already found.
    if results and not czech_competition and not profile:
        return results,'Tavily: '+primary+'; no kickoff in indexed evidence'
    # One additional search requires budget. A successful first pass must
    # remain visible even if the supplementary lookup fails.
    day_key=_budget_day or dt.datetime.now(dt.timezone.utc).strftime('%Y-%m-%d')
    with LOCK:
        cache=_read_cache(day_key)
        allowed=cache.get('tavily',0)<MAX_TAVILY_DAILY
        if allowed:
            cache['tavily']=cache.get('tavily',0)+1
            _write_cache(cache)
    if not allowed:
        return results,'Tavily: '+primary+'; kickoff retry skipped (daily limit)'
    try:
        second,detail=_tavily(fixture,transport,site_reader,_local_retry=True,
                              _budget_day=day_key,_czech_focus=czech_competition)
        return results+second,'Tavily: '+primary+'; '+detail
    except Exception as exc:
        label=('HTTP '+str(getattr(exc,'code')) if getattr(exc,'code',None)
               else type(exc).__name__)
        return results,'Tavily: '+primary+'; kickoff retry unavailable ('+label+')'


def _indexed_content_event(fixture,title,raw,reference):
    """Candidate from a small, nearby section of indexed text only.

    A full standings/results page often includes many teams, fixture dates and
    kickoffs. Search only a compact paragraph that identifies both clubs and
    the exact full date, preventing distant page elements being combined.
    """
    paragraphs=[p.strip()[:1100] for p in re.split(r'\n{2,}|\r\n\r\n',raw) if p.strip()]
    candidates=[]
    for p in paragraphs[:180]:
        if len(p)>1100:continue
        if not (_team_mentioned(fixture['home'],p) and _team_mentioned(fixture['away'],p)
                and _fixture_date_mentioned(fixture['match_date'],p)):
            continue
        found=_snippet_values(fixture,title,p,reference)
        if found:candidates.append(found)
    # Search snippets often index the date, teams, and kickoff on adjacent
    # lines rather than in a single paragraph. Check small date-centered windows
    # too; fixture-local time must still pass the Czech-site allowlist.
    seen_windows=set()
    for match in _czech_date_matches(fixture['match_date'],raw):
        start=max(0,match.start()-205)
        end=min(len(raw),match.end()+90)
        if (start,end) in seen_windows:continue
        seen_windows.add((start,end))
        window=raw[start:end]
        if not (_team_mentioned(fixture['home'],window) and
                _team_mentioned(fixture['away'],window)):
            continue
        found=_snippet_values(fixture,title,window,reference)
        if found:candidates.append(found)
    if not candidates:return {}
    # Multiple distinct entries are ambiguous (e.g. fixtures + highlights).
    collected={}
    for field in ('kickoff','country','league'):
        unique={d[field] for d in candidates if d.get(field)}
        if len(unique)==1:collected[field]=next(iter(unique))
    return collected

def _empty_cache(day):return {'day':day,'requests':0,'tavily':0,'items':{}}


def _read_cache(day):
    try:
        if CACHE.stat().st_size>500_000:return _empty_cache(day)
        data=json.loads(CACHE.read_text(encoding='utf-8'))
        if not isinstance(data,dict):return _empty_cache(day)
        if data.get('day')!=day:return _empty_cache(day)
        return data
    except (OSError,ValueError):return _empty_cache(day)


def _write_cache(data):
    temp=CACHE.with_name(CACHE.name+'.tmp')
    temp.write_text(json.dumps(data,ensure_ascii=True,separators=(',',':')),encoding='utf-8')
    os.replace(temp,CACHE)


def recover(fixture,fields,decisions=None, *, transport=None, site_reader=None, now=None, force=False):
    """Return (candidate evidence by field, diagnostics), never automatic votes.

    `transport` and `site_reader` enable full deterministic offline test coverage.
    Only missing fields are considered, and a manually selected field is never
    replaced. Cache and bounded request limits protect free/public services.
    """
    decisions=decisions or {}
    missing=[name for name in ('kickoff','country','league')
             if (fields.get(name) or {}).get('state')!='verified'
             and (decisions.get(name) or {}).get('state')!='manual']
    if not missing:return {},'All fields already verified or manually approved.'
    if not isinstance(fixture,dict) or not all(fixture.get(k) for k in ('home','away','match_date')):
        return {},'Incomplete fixture identity; no fallback search.'
    try:dt.date.fromisoformat(fixture['match_date'])
    except ValueError:return {},'Invalid fixture date; no fallback search.'
    comp=competition_for(fixture,fields,decisions)
    now=float(time.time() if now is None else now)
    day=dt.datetime.fromtimestamp(now,dt.timezone.utc).strftime('%Y-%m-%d')
    cache_key='v11-italian-reserve-review|'+ '|'.join(clean(fixture.get(k)) for k in ('id','home','away','match_date'))
    with LOCK:
        cache=_read_cache(day)
        old=cache.get('items',{}).get(cache_key)
        if old and not force and now-old.get('at',0)<(TTL if old.get('suggestions') else NEGATIVE_TTL):
            return {k:v for k,v in old.get('suggestions',{}).items() if k in missing},old.get('diagnostic','Cached free-source results.')
        if cache.get('requests',0)>=MAX_EXTERNAL_REQUESTS:return {},'Daily recovery request safety limit reached.'
        cache['requests']=cache.get('requests',0)+1
        _write_cache(cache)
    transport=transport or _download
    site_reader=site_reader or _read_site
    diagnostics=[];results=[]
    if comp:
        for label,runner in (('OpenFootball',_openfootball),):
            if not source_policy.enabled(label):
                continue
            try:
                got=runner(fixture,comp,transport)
                results.extend(got)
                diagnostics.append(label+': '+('matched fixture' if got else 'no unambiguous match'))
            except Exception as exc:
                diagnostics.append(label+': unavailable ('+type(exc).__name__+')')
    else:
        diagnostics.append('OpenFootball: league identity not known or not covered')
    with LOCK:
        cache=_read_cache(day)
        tavily_allowed=cache.get('tavily',0)<MAX_TAVILY_DAILY
        if os.environ.get('FA_TAVILY_API_KEY','').strip() and tavily_allowed:
            cache['tavily']=cache.get('tavily',0)+1
            _write_cache(cache)
        else:tavily_allowed=False
    if tavily_allowed:
        try:
            found,msg=_tavily(fixture,transport,site_reader,_budget_day=day,
                              _czech_hint=_approved_czech_route(fields, decisions))
            results.extend(found);diagnostics.append(msg)
        except Exception as exc:
            label=('HTTP '+str(getattr(exc,'code')) if getattr(exc,'code',None) else type(exc).__name__)
            diagnostics.append('Tavily: request failed ('+label+')')
    else:
        diagnostics.append('Tavily: free API key required or daily cap reached')
    # When the first providers did not know a league, a confirmed pair+date
    # web excerpt can identify one and route a second, structured dataset pass.
    if not comp:
        discovered={league_only(rec.get('values',{}).get('league')) for rec in results
                    if rec.get('values',{}).get('league')}
        if len(discovered)==1:
            league=next(iter(discovered))
            routing={'league':{'state':'review','value':'','evidence':[{'value':league}]}}
            inferred_comp=competition_for(fixture,routing,{})
            if inferred_comp:
                for label,runner in (('OpenFootball',_openfootball),):
                    if not source_policy.enabled(label):
                        continue
                    try:
                        got=runner(fixture,inferred_comp,transport)
                        results.extend(got)
                        diagnostics.append(label+' after discovery: '+('matched' if got else 'not matched'))
                    except Exception as exc:
                        diagnostics.append(label+' after discovery: '+type(exc).__name__)
    # Wikimedia is already wired to sr_logo_discovery.wikidata and optional
    # Wikimedia Commons candidate discovery for CRESTS, not date/time/league votes.
    diagnostics.append('Wikidata/Wikimedia: available through existing team-crest recovery')
    collected={k:[] for k in missing}
    seen=set()
    for record in results:
        for field in missing:
            val=clean(record['values'].get(field))
            if not val:continue
            key=(record['source'],field,val)
            if key in seen:continue
            seen.add(key)
            candidate={'source':record['source'],'value':val,
                       'reference':record['reference'],'recovery':True}
            if record.get('identityReview'):
                candidate.update(identityReview=True,
                                 identityReason=record.get('identityReason','review_identity'),
                                 sourceHome=record.get('sourceHome',''),
                                 sourceAway=record.get('sourceAway',''))
            collected[field].append(candidate)
    collected={k:v for k,v in collected.items() if v}
    diagnosis='; '.join(diagnostics)
    with LOCK:
        cache=_read_cache(day)
        cache.setdefault('items',{})[cache_key]={'at':now,'suggestions':collected,'diagnostic':diagnosis}
        if len(cache['items'])>MAX_CACHE:
            for key in sorted(cache['items'],key=lambda k:cache['items'][k].get('at',0))[:40]:
                del cache['items'][key]
        _write_cache(cache)
    return collected,diagnosis
