"""Opt-in, bounded official-fixture web recovery for SoccerRating queue metadata.

Search is supplied by the official Brave Search API (FA_BRAVE_SEARCH_KEY).
Only robots-permitted, allowlisted HTTPS official competition/federation sites
and their public SportsEvent JSON-LD are read. Results are suggestions ONLY:
they never become verification votes or change previously approved values.
No access to Sofascore, browser profiles, or unrelated project databases.
"""
from __future__ import annotations

import datetime as dt
import json
import os
import re
import threading
import time
from html.parser import HTMLParser
from pathlib import Path
import sr_fixture_identity as identity  # PHASE4_UNIFIED_IDENTITY
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode, urlsplit
from urllib.request import Request, build_opener, HTTPRedirectHandler
from urllib.robotparser import RobotFileParser

ROOT = Path(__file__).resolve().parent
CACHE = ROOT / 'soccerrating_web_recovery_cache.json'
DAILY_MAX = 20  # defensive cap lower than provider's advertised monthly credits
MAX_PAGES = 3
CACHE_SECONDS = 12 * 3600
LOCK = threading.RLock()
AGENT = 'FootballAnalyticsFixtureResearch/1.0'
# Official fixture sources only, not random third-party scraped pages.
OFFICIAL_DOMAINS = (
    'jleague.jp', 'jfa.jp', 'bundesliga.com', 'premierleague.com',
    'laliga.com', 'legaseriea.it', 'ligue1.com', 'mlssoccer.com',
    'uefa.com', 'fifa.com', 'the-afc.com', 'thefa.com', 'dfb.de',
    'efl.com', 'scottishfa.co.uk', 'eredivisie.nl', 'ligaportugal.pt',
    'cbf.com.br', 'afa.com.ar', 'footballaustralia.com.au',
)


def safe_url(url):
    """Never follow an arbitrary URL/redirect or load localhost from index results."""
    try:
        u = urlsplit(str(url))
        if u.scheme != 'https' or u.username or u.password or u.port not in (None,443): return False
        host=(u.hostname or '').lower().rstrip('.')
        if not host or len(url)>800: return False
        return any(host == allowed or host.endswith('.'+allowed) for allowed in OFFICIAL_DOMAINS)
    except ValueError: return False


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def read_public_event_page(url, *, permitted=None):
    if not safe_url(url): raise ValueError('Not an allowlisted official HTTPS fixture page')
    if permitted is None:
        host=urlsplit(url).hostname
        robots_url='https://'+host+'/robots.txt'
        try:
            request=Request(robots_url,headers={'User-Agent':AGENT})
            with build_opener(NoRedirect).open(request,timeout=6) as resp:
                if resp.status != 200:raise ValueError('Robots rules unavailable')
                rules=resp.read(110_000).decode('utf-8','replace').splitlines()
            rp=RobotFileParser();rp.parse(rules)
            permitted=rp.can_fetch(AGENT,url)
        except Exception:
            permitted=False  # fail closed, do not infer permission
    if not permitted: raise ValueError('Official site does not permit automated reading')
    with build_opener(NoRedirect).open(Request(url,headers={
            'User-Agent':AGENT,'Accept':'text/html,application/xhtml+xml'}),timeout=10) as resp:
        if resp.status != 200:raise ValueError('Page unavailable')
        if 'html' not in (resp.headers.get('Content-Type') or '').lower():raise ValueError('Not an HTML page')
        if int(resp.headers.get('Content-Length') or 0)>260_000:raise ValueError('HTML page exceeds safe size')
        data=resp.read(260_001)
        if len(data)>260_000:raise ValueError('HTML page exceeds safe size')
        return data.decode('utf-8','replace')


class EventScripts(HTMLParser):
    def __init__(self):
        super().__init__();self.inside=False;self.parts=[];self.scripts=[]
    def handle_starttag(self,tag,attrs):
        if tag=='script' and dict(attrs).get('type','').lower().startswith('application/ld+json'):
            self.inside=True;self.parts=[]
    def handle_data(self,data):
        if self.inside:self.parts.append(data)
    def handle_endtag(self,tag):
        if tag=='script' and self.inside:
            self.inside=False;self.scripts.append(''.join(self.parts));self.parts=[]


def objects(value,limit=160):
    queue=[value];i=0
    while queue and i<limit:
        node=queue.pop(0);i+=1
        if isinstance(node,list):queue.extend(node[:40]);continue
        if not isinstance(node,dict):continue
        yield node
        for k in ('@graph','itemListElement','mainEntity','event','events'):
            if isinstance(node.get(k),(dict,list)):queue.append(node[k])


def text_name(obj):
    if isinstance(obj,dict):return str(obj.get('name') or obj.get('legalName') or '')
    return str(obj or '')


def clean(value):
    return re.sub(r'\s+',' ',str(value or '').strip())[:160]


def league_only(text):
    s=clean(text)
    # Never append matchweek, round or stage numbers to the League field.
    s=re.sub(r'\s*[-–|,]\s*(?:matchweek|matchday|round|week|md|stage)\s*#?\d+.*$','',s,flags=re.I)
    s=re.sub(r'\s*[-–|,]\s*\d+\.?\s*(?:spieltag|round|matchweek).*$','',s,flags=re.I)
    return s[:100]


def utc_time(raw):
    try:
        value=dt.datetime.fromisoformat(str(raw).replace('Z','+00:00'))
        if value.tzinfo is None:return ''
        return value.astimezone(dt.timezone.utc).strftime('%Y-%m-%d %H:%M')
    except (TypeError,ValueError):return ''


def extract(html,fixture,url,*,names_match=None):
    """Match both clubs + match date before accepting ANY page metadata.

    Ambiguous match identities and unsupported timezone fields produce nothing.
    """
    if not safe_url(url):return {}
    # A supplied matcher is retained for backwards-compatible isolated tests;
    # the production parser always uses the centralized fixture identity.
    parser=EventScripts()
    parser.feed(html[:260_000])
    match_date=dt.date.fromisoformat(fixture['match_date'])
    matches=[]
    for script in parser.scripts[:30]:
        try:decoded=json.loads(script)
        except (ValueError,TypeError):continue
        for item in objects(decoded):
            typ=item.get('@type') or []
            if not isinstance(typ,list):typ=[typ]
            if not any(str(x).split('/')[-1].lower()=='sportsevent' for x in typ):continue
            h=text_name(item.get('homeTeam'));a=text_name(item.get('awayTeam'))
            kickoff=utc_time(item.get('startDate'))
            if not kickoff or kickoff[:10]!=match_date.isoformat():continue
            if names_match is not None:
                if not (h and a and names_match(fixture['home'],h)
                        and names_match(fixture['away'],a)):continue
            else:
                match=identity.source_fixture(fixture,h,a,kickoff[:10])
                if match.classification=='reject':continue
            competition=item.get('superEvent') or item.get('sportsCompetition') or {}
            league=league_only(text_name(competition))
            # Only a specifically identified competition's location is a possible
            # country field; venue country is NOT competition nationality.
            country=''
            if isinstance(competition,dict):
                address=(competition.get('location') or {}).get('address') if isinstance(competition.get('location'),dict) else {}
                if isinstance(address,dict):country=clean(text_name(address.get('addressCountry')))
            match={'kickoff':kickoff,'league':league,'country':country}
            if match not in matches:matches.append(match)
    # No arbitrary first-match selection in case of conflicting event metadata.
    return matches[0] if len(matches)==1 else {}


def api_search(query,key):
    from urllib.request import urlopen
    url='https://api.search.brave.com/res/v1/web/search?'+urlencode({'q':query,'count':10})
    req=Request(url,headers={'X-Subscription-Token':key,'Accept':'application/json','User-Agent':AGENT})
    with urlopen(req,timeout=12) as resp:
        if resp.status!=200:raise ValueError('Search provider unavailable')
        result=json.loads(resp.read(450_000))
    return [x.get('url','') for x in ((result.get('web') or {}).get('results') or []) if isinstance(x,dict)]


def _read_cache():
    try:
        if CACHE.stat().st_size>300_000:return {'day':'','used':0,'items':{}}
        data=json.loads(CACHE.read_text(encoding='utf-8'))
        if not isinstance(data,dict):raise ValueError
        return data
    except (OSError,ValueError):return {'day':'','used':0,'items':{}}


def _write_cache(data):
    temporary=CACHE.with_suffix('.recovery_tmp')
    temporary.write_text(json.dumps(data,separators=(',',':')),encoding='utf-8')
    os.replace(temporary,CACHE)


def recover(fixture,fields,decisions=None,*,search=None,fetch=None,now=None,force=False):
    """Return (suggestions per missing field, safe diagnostics).

    No autonomous verification or database writes; web-search results never
    enter four-source voting and never override manual decisions.
    """
    wanted=[f for f in ('kickoff','country','league') if
            fields.get(f,{}).get('state')!='verified' and
            (force or (decisions or {}).get(f,{}).get('state')!='manual')]
    if not wanted:return {},'All metadata already verified or manually selected.'
    token=os.environ.get('FA_BRAVE_SEARCH_KEY','').strip()
    live_mode = search is None
    if live_mode and not token:return {},'Web search requires optional FA_BRAVE_SEARCH_KEY; four existing sources are unaffected.'
    if live_mode:search=lambda query:api_search(query,token)
    if fetch is None:fetch=read_public_event_page
    now=float(now if now is not None else time.time())
    day=dt.datetime.fromtimestamp(now,dt.timezone.utc).strftime('%Y-%m-%d')
    cache_key='|'.join(clean(fixture.get(k)) for k in ('id','home','away','match_date'))
    with LOCK:
        c=_read_cache()
        if c.get('day')!=day:c={'day':day,'used':0,'items':{}}
        entry=c.get('items',{}).get(cache_key)
        if entry and not force and now-entry.get('at',0)<CACHE_SECONDS:
            return {key:val for key,val in entry.get('suggestions',{}).items() if key in wanted},'Reused cached official-site search results.'
        if int(c.get('used',0))>=DAILY_MAX and live_mode:
            return {},'Official web lookup daily safety quota reached.'
        # Count requests before network call so failures do not bypass quotas.
        c['used']=int(c.get('used',0))+1
        _write_cache(c)
    query='"'+clean(fixture['home'])+'" "'+clean(fixture['away'])+'" '+str(fixture['match_date'])+' official match kickoff'
    try:
        urls=search(query)
    except Exception as exc:
        return {},'Search provider unavailable ('+type(exc).__name__+').'
    output={key:[] for key in wanted};accepted=0;seen=set()
    for url in urls[:12]:
        if accepted>=MAX_PAGES:break
        if not safe_url(url):continue
        hostname=(urlsplit(url).hostname or '').lower()
        if hostname in seen:continue
        seen.add(hostname)
        try:
            html=fetch(url)
            obj=extract(html,fixture,url)
        except Exception:continue
        if not obj:continue
        for field in wanted:
            val=clean(obj.get(field))
            if val:
                output[field].append({'source':'Official web · '+hostname,'value':val,'reference':url,'recovery':True})
        accepted+=1
    output={key:val for key,val in output.items() if val}
    with LOCK:
        c=_read_cache();c.setdefault('items',{})[cache_key]={'at':now,'suggestions':output}
        if len(c['items'])>150:
            oldest=sorted(c['items'],key=lambda k:c['items'][k].get('at',0))[:50]
            for k in oldest:c['items'].pop(k,None)
        _write_cache(c)
    return output,(f'{accepted} official fixture page(s) matched; suggestions require manual approval.'
                   if output else 'No matching permitted official SportsEvent pages found; fields remain available for manual import.')
