"""Approved 16-source Football Analytics fixture research adapter, v1.

Eight original sources remain unchanged. New providers produce *manual research
suggestions only*, never automatic votes or silent imports. Keyless historical
sources are registered but never polled for live queue fixtures. Credentials
come from process environment ONLY, in HTTPS headers; never logged or saved.

Only API Ninjas (league-specific) and Bzzoiro (team/date-specific) have enough
public current docs to implement provisional bounded HTTP adapters. Live
response schema, entitlement, coverage and original SoccerRating category
must still be validated when account tokens become available.
"""
from __future__ import annotations
from datetime import date,datetime,timedelta,timezone
from pathlib import Path
from urllib.parse import urlencode,urlsplit
from urllib.request import Request,build_opener,HTTPRedirectHandler
from contextlib import closing
import json,os,re,threading,sqlite3
from sr_fixture_identity import source_fixture,category
import sr_unified_evidence_contract as unified
import sr_source_policy as source_policy  # FA_SR_SOURCE_CLEANUP_8_OF_16_20261122

ROOT=Path(__file__).resolve().parent
BUDGET=ROOT/'soccerrating_added_source_budget.json'
LOCK=threading.RLock()
CAPS={'API Ninjas Football':12,'Bzzoiro Sports Data':18}
KEYS={
    'Sportmonks':'FA_SPORTMONKS_TOKEN',
    'API Ninjas Football':'FA_API_NINJAS_KEY',
    'SportsAPI360':'FA_SPORTSAPI360_KEY',
    'Bzzoiro Sports Data':'FA_BSD_TOKEN',
    'BeSoccer API':'FA_BESOCCER_KEY',
    'GoalServe':'FA_GOALSERVE_KEY',
}
API_LEAGUES={
    ('sweden','allsvenskan'):('allsvenskan','Sweden','Swedish Allsvenskan'),
    ('sweden','swedish allsvenskan'):('allsvenskan','Sweden','Swedish Allsvenskan'),
    ('england','premier league'):('epl','England','Premier League'),
    ('germany','bundesliga'):('bundesliga','Germany','Bundesliga'),
    ('scotland','scottish premiership'):('scottishpremiership','Scotland','Scottish Premiership'),
    ('denmark','danish superliga'):('danishsuperliga','Denmark','Danish Superliga'),
}
# This first-party provenance is already in existing review evidence. It only
# narrows search routing; does NOT establish the original SW1 gender/category.
FIRST_PARTY_HINTS={
    ('Official Halmstads BK mens fixture',
     'www.hbk.se',
     'sweden','swedish allsvenskan'),
}
MAX_JSON=1_200_000
# Persist only previously inspected first-party fixture choices. They remain
# user-review suggestions and never supply votes or approvals on rescan.
RETAINED_FIRST_PARTY={
    'Official Halmstads BK mens fixture':(
       'https://www.hbk.se/nyheter/2026/november/matchguide-brommapojkarna-hbk',
       'IF Brommapojkarna','Halmstads BK'),
    'Official Campeonato Chileno fixture':(
       'https://www.campeonatochileno.cl/match/deportes-limache-deportes-la-serena-2026-11-22/',
       'Deportes Limache','Deportes La Serena'),
}
def preserved_first_party_choices(fixture,old_fields,key):
    """Copy only recognized, date/team/URL-scoped old manual evidence."""
    if key not in ('kickoff','country','league'):return []
    saved=(old_fields.get(key) or {}).get('evidence') or []
    kept=[]
    for e in saved:
        if not isinstance(e,dict) or e.get('identityReview') is not True:continue
        expected=RETAINED_FIRST_PARTY.get(e.get('source'))
        if not expected or e.get('reference')!=expected[0]:continue
        allowed_raw_away={_norm(expected[2])}
        if e.get('source')=='Official Campeonato Chileno fixture':
            allowed_raw_away.add(_norm('CD La Serena'))
        if (str(e.get('sourceHome') or '')!=expected[1] or
            str(e.get('sourceAway') or '')!=expected[2] or
            _norm(fixture.get('home'))!=_norm(expected[1]) or
            _norm(fixture.get('away')) not in allowed_raw_away or
            e.get('sourceDate')!=fixture.get('match_date')):continue
        if not e.get('value'):continue
        kept.append(dict(e))
    return kept

def _norm(value):
    import unicodedata
    value=unicodedata.normalize('NFKD',str(value or '').casefold())
    value=''.join(c for c in value if not unicodedata.combining(c))
    return re.sub(r'[^a-z0-9]+',' ',value).strip()

def _utc(value):
    if not isinstance(value,str) or len(value)>50:return ''
    try:
        stamp=datetime.fromisoformat(value.replace('Z','+00:00'))
        if stamp.tzinfo is None:return ''
        return stamp.astimezone(timezone.utc).strftime('%Y-%m-%d %H:%M')
    except (ValueError,OverflowError):return ''

def _name(value):
    if isinstance(value,dict):
        return str(value.get('name') or value.get('display_name') or '')[:130]
    if isinstance(value,str):return value.strip()[:130]
    return ''

def _date(value):
    try:return date.fromisoformat(str(value or ''))
    except (ValueError,TypeError):return None

def _approved_context(fixture,fields,decisions):
    """Trusted original, verified or approved country+league, no conflicts."""
    country=[str(fixture.get('country') or '').strip()]
    league=[str(fixture.get('league') or '').strip()]
    for key,values in (('country',country),('league',league)):
        manual=(decisions.get(key) or {})
        verified=(fields.get(key) or {})
        if manual.get('state')=='manual':values.append(str(manual.get('value') or '').strip())
        if verified.get('state')=='verified':values.append(str(verified.get('value') or '').strip())
    ck={_norm(x) for x in country if x}
    lk={_norm(x) for x in league if x}
    if len(ck)==1 and len(lk)==1:
        return next(iter(ck)),next(iter(lk))
    return None

def _first_party_hint(fixture,fields):
    # Never infer from plain 'Premier League' or an untrusted indexed snippet.
    for source,host,country,league in FIRST_PARTY_HINTS:
        ce=(fields.get('country') or {}).get('evidence') or []
        le=(fields.get('league') or {}).get('evidence') or []
        pair=[e for e in ce+le if e.get('source')==source and
              urlsplit(str(e.get('reference') or '')).hostname==host and
              _norm(e.get('sourceHome'))==_norm(fixture.get('home')) and
              _norm(e.get('sourceAway'))==_norm(fixture.get('away')) and
              e.get('sourceDate')==fixture.get('match_date')]
        if any(_norm(e.get('value'))==country for e in pair) and any(
              _norm(e.get('value'))==league for e in pair):
            return country,league
    return None

def _competition(fixture,fields,decisions):
    context=_approved_context(fixture,fields,decisions)
    # Never use an official hint if it contradicts ANY original trusted field.
    official=_first_party_hint(fixture,fields)
    raw_country=_norm(fixture.get('country'))
    raw_league=_norm(fixture.get('league'))
    if not context and official:
        trusted_country=[raw_country]
        trusted_league=[raw_league]
        for key,values in (('country',trusted_country),('league',trusted_league)):
            manual=(decisions.get(key) or {})
            verified=(fields.get(key) or {})
            if manual.get('state')=='manual':values.append(_norm(manual.get('value')))
            if verified.get('state')=='verified':values.append(_norm(verified.get('value')))
        if any(x and x!=official[0] for x in trusted_country):return None
        if any(x and x!=official[1] for x in trusted_league):return None
        context=official
    return API_LEAGUES.get(context)

def configured_status(environ=None):
    """All eight new providers, even when no access is configured."""
    environ=environ if environ is not None else os.environ
    output={}
    for source in unified.ADDED_SOURCES:
        if not source_policy.enabled(source):
            output[source]={'status':'disabled_by_policy',
                            'reason':'Archived from live fixture discovery; historical records retained',
                            'attempted':False,'fields':[]}
            continue
        variable=KEYS.get(source)
        active=bool((environ.get(variable,'') if variable else '').strip())
        if source=='StatsBomb Open Data':
            status,reason='historical_only','Open historical events; not an upcoming fixture feed'
        elif source=='Football-Data.co.uk':
            status,reason='keyless_access_unverified','Weekly fixture CSV last returned HTTP 406; do not claim live coverage'
        elif source=='BeSoccer API':
            status,reason='trial_or_paid_required','Provider states no permanent free accounts'
        elif source=='GoalServe':
            status,reason='trial_or_paid_required','Commercial or trial key and access entitlement required'
        elif source=='Sportmonks':
            status,reason=('plan_scope_unchecked','Free access limited to Danish and Scottish leagues') if active else (
               'key_required','Configure FA_SPORTMONKS_TOKEN; free plan has two leagues')
        elif source=='SportsAPI360':
            status,reason=('schema_validation_pending','Do not spend 100/month quota until schema confirmed') if active else (
               'key_required','Configure FA_SPORTSAPI360_KEY; free cap 100/month')
        elif source=='API Ninjas Football':
            status,reason=('ready_for_fixture_research','Free current season, league-specific') if active else (
               'key_required','Configure FA_API_NINJAS_KEY; current-season fixture API')
        elif source=='Bzzoiro Sports Data':
            status,reason=('ready_for_fixture_research','Free token; verify specific league coverage') if active else (
               'key_required','Configure FA_BSD_TOKEN; 7500/day free football allowance')
        else:
            status,reason='not_reported','Unknown provider'
        output[source]={'status':status,'reason':reason,'attempted':False,'fields':[]}
    return output

class _NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):return None

def _request(url,headers):
    host=urlsplit(url)
    if (host.scheme!='https' or host.hostname not in
      {'api.api-ninjas.com','sports.bzzoiro.com'}):
        raise ValueError('Provider endpoint not allowlisted')
    req=Request(url,headers={'Accept':'application/json',
                'User-Agent':'FootballAnalyticsReviewOnly/1.0',**headers})
    with build_opener(_NoRedirect).open(req,timeout=12) as resp:
        if resp.status!=200:raise ValueError('Provider returned non-200')
        body=resp.read(MAX_JSON+1)
        if len(body)>MAX_JSON:raise ValueError('Provider JSON exceeds bound')
        return json.loads(body)

def _reserve(source,now=None,budget=None):
    if source not in CAPS:return False
    now=now or datetime.now(timezone.utc)
    f=budget or BUDGET
    with LOCK:
        try:
            state=json.loads(f.read_text(encoding='utf-8'))
            if not isinstance(state,dict):state={}
        except (OSError,ValueError):state={}
        stamp=now.strftime('%Y-%m-%d')
        counts=state.get('counts') if state.get('day')==stamp else {}
        counts=dict(counts) if isinstance(counts,dict) else {}
        used=int(counts.get(source,0))
        if used>=CAPS[source]:return False
        counts[source]=used+1
        next_state={'day':stamp,'counts':counts}
        tmp=f.with_name(f.name+'.tmp')
        tmp.write_text(json.dumps(next_state,separators=(',',':')),encoding='utf-8')
        os.replace(tmp,f)
        return True

def _parse_ninjas(data,fixture,comp):
    """Return one unambiguous oriented fixture or none; no fallback guessing."""
    if not isinstance(data,list):return []
    league_code,country,league=comp
    possibilities=[]
    for r in data[:70]:
        if not isinstance(r,dict) or r.get('league')!=league_code:continue
        if r.get('sport') not in ('soccer',None):continue
        home=_name(r.get('home_team'));away=_name(r.get('away_team'))
        stamp=_utc(r.get('start_time'))
        localday=_date(r.get('date'))
        if not (home and away and stamp and localday and r.get('game_id')):continue
        checked=source_fixture(fixture,home,away,localday.isoformat(),country=country,league=league)
        if checked.classification=='reject':continue
        if abs((localday-_date(fixture['match_date'])).days)>1:continue
        possibilities.append({'home':home,'away':away,'kickoff':stamp,'country':country,'league':league,
          'original_source_date':fixture['match_date'],'source_date':localday.isoformat(),
          'event_id':str(r['game_id'])[:95],
          'home_id':str((r.get('home_team') or {}).get('team_id') or '')[:70],
          'away_id':str((r.get('away_team') or {}).get('team_id') or '')[:70]})
    return possibilities if len(possibilities)==1 else []

def _official_chile_alias_review(fixture,fields,home,away,utc,decisions=None):
    """A *manual-only* exception for one independently documented Chile event.

    No new alias is verified or imported. A source-name variant is shortlisted
    only when official federation home/away/date/UTC evidence agrees, both
    names are proposed on ONE Reep men's team, and protected categories agree.
    It is NEVER eligible to cast an automatic source vote.
    """
    if (not fields or category(fixture.get('home')) or
        category(fixture.get('away')) or category(home) or category(away)):
        return False
    if _norm(fixture.get('home'))!=_norm(home):return False
    if _norm(fixture.get('away'))==_norm(away):return False
    source_day=_date(fixture.get('match_date'))
    utc_day=_date(utc[:10])
    if not source_day or not utc_day or abs((source_day-utc_day).days)>1:
        return False
    official='Official Campeonato Chileno fixture'
    reference='https://www.campeonatochileno.cl/match/deportes-limache-deportes-la-serena-2026-11-22/'
    expected={'kickoff':utc,'country':'Chile','league':'Chile Primera Division'}
    decisions=decisions or {}
    for key,value in expected.items():
        if key in ('country','league'):
            trusted=[str(fixture.get(key) or '').strip()]
            manual=decisions.get(key) or {}
            verified=fields.get(key) or {}
            if manual.get('state')=='manual':trusted.append(str(manual.get('value') or '').strip())
            if verified.get('state')=='verified':trusted.append(str(verified.get('value') or '').strip())
            if any(v and _norm(v)!=_norm(value) for v in trusted):return False
        evidence=(fields.get(key) or {}).get('evidence') or []
        if not any(e.get('source')==official and e.get('reference')==reference and
                e.get('identityReview') is True and e.get('value')==value and
                e.get('sourceDate')==fixture.get('match_date') and
                _norm(e.get('sourceHome'))==_norm(home) and
                _norm(e.get('sourceAway'))==_norm(away) for e in evidence):
            return False
    # The original participant name must have a concrete, category-scoped
    # corroboration. Proposed aliases alone are NOT verification: in this
    # function they serve only to shortlist a first-party-confirmed review.
    import team_identity_registry as registry
    db=(ROOT/'team_identity_registry.db')
    if not db.is_file():return False
    try:
        with closing(sqlite3.connect(db.resolve().as_uri()+'?mode=ro',
                                     uri=True,timeout=5)) as c:
            c.execute('PRAGMA query_only=ON')
            def claims(raw):
                return c.execute('''SELECT DISTINCT t.team_id,t.gender,t.category
                    FROM aliases a JOIN teams t ON t.team_id=a.team_id
                    WHERE a.name_key=? AND t.source='Reep' AND
                    t.country_key='chile' ''',(registry.norm(raw),)).fetchall()
            original=claims(fixture.get('away'))
            provider=claims(away)
            if any((gender or '').lower()!='men' or (cat or '')!=''
                   for _,gender,cat in original+provider):
                return False
            common={t for t,_,_ in original}&{t for t,_,_ in provider}
            return len(common)==1 and bool(original) and bool(provider)
    except (sqlite3.Error,OSError):
        return False

def _parse_bsd(data,fixture,fields=None,decisions=None):
    """Bounded real Bzzoiro rows; one exact match OR scoped manual review."""

    if not isinstance(data,dict) or not isinstance(data.get('results'),list):return []
    if int(data.get('count',0) or 0)>50:return [] # avoid incomplete page as exhaustive proof
    possibilities=[]
    for r in data['results'][:50]:
        if not isinstance(r,dict) or not r.get('id'):continue
        home=_name(r.get('home_team'));away=_name(r.get('away_team'))
        raw=r.get('event_date')
        stamp=_utc(raw)
        if not (home and away and stamp):continue
        day=_date(stamp[:10])
        if not day or abs((day-_date(fixture['match_date'])).days)>1:continue
        league=_name(r.get('league')) or _name(r.get('league_name'))
        country=_name(r.get('country'))
        checked=source_fixture(fixture,home,away,day.isoformat(),country=country,league=league)
        official_alias_review=False
        if checked.classification=='reject':
            official_alias_review=_official_chile_alias_review(fixture,fields,home,away,stamp,decisions)
            if not official_alias_review:continue
        values={'home':home,'away':away,'kickoff':stamp,'source_date':day.isoformat(),
                'event_id':str(r['id'])[:75]}
        if league:values['league']=league
        if country:values['country']=country
        if official_alias_review:
            values['alias_corroboration']='official_federation_and_single_reep_mens_identity_review_only'
        possibilities.append(values)
    return possibilities if len(possibilities)==1 else []

def _as_review(source,item,reference):
    values={k:item[k] for k in ('kickoff','country','league') if item.get(k)}
    if not values:return []
    return [{'source':source,'reference':reference,'values':values,
             'identityReview':True,'identityReason':(
                'independent_source_fixture_identity_for_manual_review_only; '
                'original_SoccerRating_competition_and_category_unverified'),
             'sourceHome':item['home'],'sourceAway':item['away'],
             'sourceEventId':item['event_id'],
             'sourceDate':item.get('source_date',''),
             'sourceIdentityReviewReason':item.get('alias_corroboration','') }]

def recover(fixture,fields,decisions=None,*,environ=None,transport=None,reserve=None,now=None):
    """Return (field -> safe evidence choices, eight source statuses).

    No key -> no outbound request and no quota ledger mutation.
    With key -> only fixed bounded authenticated HTTPS GETs, one per provider.
    No caller can turn returned evidence into auto provider votes.
    """
    environ=environ if environ is not None else os.environ
    decisions=decisions or {}
    statuses=configured_status(environ)
    out={key:[] for key in ('kickoff','country','league')}
    if not isinstance(fixture,dict) or not all(fixture.get(k) for k in ('home','away','match_date')):
        return {},statuses
    source_day=_date(fixture.get('match_date'))
    if source_day is None:return {},statuses
    # Do not search or show already approved data for forced replacement.
    missing={key for key in out if (fields.get(key) or {}).get('state')!='verified'
              and (decisions.get(key) or {}).get('state')!='manual'}
    if not missing:return {},statuses
    request=transport or _request
    charge=reserve or (lambda source:_reserve(source,now=now))
    searches=[]
    ninjas=environ.get(KEYS['API Ninjas Football'],'').strip()
    comp=_competition(fixture,fields,decisions)
    if ninjas and source_policy.enabled('API Ninjas Football') and comp:
        league,country,leaguename=comp
        url='https://api.api-ninjas.com/v1/soccermatches?'+urlencode({
              'league':league,'date':fixture['match_date']})
        searches.append(('API Ninjas Football',url,{'X-Api-Key':ninjas},
                lambda payload:_parse_ninjas(payload,fixture,comp)))
    elif ninjas:
        statuses['API Ninjas Football'].update(status='trusted_competition_required',
                  reason='No safe country+league route; skip unqualified data')
    bsd=environ.get(KEYS['Bzzoiro Sports Data'],'').strip()
    if bsd and source_policy.enabled('Bzzoiro Sports Data'):
        url='https://sports.bzzoiro.com/api/v2/events/?'+urlencode({
              'team_name':fixture['home'][:90],
              'date_from':(source_day-timedelta(days=1)).isoformat(),
              'date_to':(source_day+timedelta(days=1)).isoformat(),
              'limit':50})
        searches.append(('Bzzoiro Sports Data',url,{'Authorization':'Token '+bsd},
                lambda payload:_parse_bsd(payload,fixture,fields,decisions)))
    for source,url,headers,parser in searches:
        if not charge(source):
            statuses[source].update(status='local_request_cap',reason='Conservative daily request cap reached')
            continue
        try:
            payload=request(url,headers)
            matches=parser(payload)
            if not matches:
                statuses[source].update(status='no_safe_unique_match',reason='No unique oriented/date-verified event in bounded result',attempted=True)
                continue
            base=url.split('?')[0] # no account token ever in URL or report
            evidence=_as_review(source,matches[0],base)
            for row in evidence:
                for key,val in row['values'].items():
                    if key in missing:
                        out[key].append({'source':source,'reference':row['reference'],
                           'value':val,'recovery':True,'identityReview':True,
                           'identityReason':row['identityReason'],
                           'sourceHome':row['sourceHome'],'sourceAway':row['sourceAway'],
                           'sourceEventId':row['sourceEventId'],'sourceDate':row['sourceDate'],
                           'sourceIdentityReviewReason':row.get('sourceIdentityReviewReason','')})
            statuses[source].update(status='review_evidence',reason='Unique provider match; human category review required',
                                   attempted=True,fields=sorted(set(matches[0])&missing))
        except Exception as exc:
            # Exception type only: never include credential-bearing headers/body.
            statuses[source].update(status='request_unavailable',
                reason='Provider request or schema failed ('+type(exc).__name__+')',attempted=True)
    return {k:v for k,v in out.items() if v},statuses
