"""Unified eight-source identity and evidence contract.

All eight sources can submit one normalized evidence record. Whether a field is
present and whether identity may be automatically verified are separate facts.
No provider is allowed to manufacture fields outside its actual output.
"""
from __future__ import annotations
from dataclasses import asdict
from urllib.parse import urlsplit
from sr_fixture_identity import source_fixture

EIGHT_SOURCES=(
    'API-Football','TheSportsDB','ESPN','football-data.org',
    'OpenLigaDB','OpenFootball','Wikidata/Wikimedia','Tavily')
# FA_EXPANDED_UNIFIED_SOURCES_V1: preserve the original eight-provider
# compatibility contract, add exactly eight NEW identifiers without duplicates.
# Registration is not access/availability/voting certification.
ADDED_SOURCES=(
    'Sportmonks','API Ninjas Football','SportsAPI360','Bzzoiro Sports Data',
    'StatsBomb Open Data','Football-Data.co.uk','BeSoccer API','GoalServe')
ALL_SOURCES=EIGHT_SOURCES+ADDED_SOURCES
assert len(ALL_SOURCES)==16 and len(set(ALL_SOURCES))==16
SIX_FIELDS=('kickoff','country','league','countryLogo','homeLogo','awayLogo')
# Compatibility: the old quorum rule is NOT changed by this preview.
AUTO_VOTE_CAPABILITIES={
    'API-Football':{'kickoff','country','league'},
    'TheSportsDB':{'kickoff','country','league'},
    'ESPN':{'kickoff','country','league'},
    'football-data.org':{'kickoff','country','league'},
    'OpenLigaDB':set(),'OpenFootball':set(),'Wikidata/Wikimedia':set(),'Tavily':set(),
    # None of the eight added providers may supply an automatic vote until its
    # real schema, rights, source identity, category and quorum rules pass QA.
    **{provider:set() for provider in ADDED_SOURCES},
}

def canonical_publisher(reference):
    try:
        u=urlsplit(str(reference or ''))
        if u.scheme not in ('https','http'):return ''
        return (u.hostname or '').lower().removeprefix('www.')
    except (TypeError,ValueError):return ''

def assess_record(fixture:dict,record:dict,*,verified_aliases=None) -> dict:
    """Classify a source record; no quota use, network, I/O or approvals.

    Required record keys: provider, home, away, match_date, fields (dict).
    Records missing source club identities must be held for manual research,
    not silently treated as a match because their URL mentions a team.
    """
    provider=record.get('provider','')
    if provider not in ALL_SOURCES:
        return {'status':'reject','reason':'unknown_provider','provider':provider,'fields':{}}
    ref=record.get('reference','')
    src_fixture={k:record.get(k) for k in ('home','away','match_date','country','league')}
    result=source_fixture(fixture,src_fixture.get('home'),src_fixture.get('away'),
                          src_fixture.get('match_date'),country=src_fixture.get('country'),
                          league=src_fixture.get('league'),aliases=verified_aliases)
    extracted={k:v for k,v in (record.get('fields') or {}).items() if k in SIX_FIELDS and v not in (None,'')}
    if result.classification=='reject':
        return {'status':'reject','reason':result.reason,'provider':provider,'fields':{}}
    # No guessed values, no extra vote from one publisher under a different label.
    voting_fields=sorted(set(extracted) & AUTO_VOTE_CAPABILITIES[provider]) if result.classification=='match' else []
    return {'status':'accepted' if result.classification=='match' else 'review',
            'reason':result.reason, 'provider':provider, 'publisher':canonical_publisher(ref),
            'reference':ref,'fields':extracted,'autoVoteFields':voting_fields,
            'identity':asdict(result)}

def independent_voters(records:list[dict], field:str) -> set[str]:
    """Each provider can contribute at most one voter for a field.

    The old four-provider quorum remains untouched. Third-party web excerpts
    are always review only, regardless of how many pages/references they use.
    """
    if field not in SIX_FIELDS:return set()
    return {row['provider'] for row in records
            if row.get('status')=='accepted' and field in row.get('autoVoteFields',[])}


def source_health_snapshot(core_health=None, recovered=None, artwork=None, extended_status=None):
    """One source snapshot; legacy callers retain the original eight layout.

    Providing extended_status (even empty) opts into the unified 16-source
    inventory; missing key/plan must never be misreported as 'no match'.
    """
    core=(core_health or {}).get('core',{})
    records={}
    inventory=ALL_SOURCES if extended_status is not None else EIGHT_SOURCES
    for provider in inventory:
        if provider in core:
            row=core[provider]
            records[provider]={'status':row.get('status','not_reported'),
                               'reason':row.get('reason',''),
                               'attempted':bool(row.get('attempted')),
                               'fields':list(row.get('fields',[]))}
        else:
            records[provider]={'status':'not_reported','reason':'not_in_current_scan',
                               'attempted':False,'fields':[]}
    for field,items in (recovered or {}).items():
        for item in items:
            source=item.get('source')
            if str(source).startswith('Tavily'):
                source='Tavily'
            if source in records:
                records[source]['status']='evidence'
                records[source]['fields']=sorted(set(records[source]['fields']) | {field})
    # Artwork discovery runs independently of fixture scan. Its outcome is not
    # inferred from 'Wikidata/Wikimedia exists'. Do not mark it as attempted.
    for source,metadata in (artwork or {}).items():
        if source in records and isinstance(metadata,dict):
            records[source].update(metadata)
    for provider,info in (extended_status or {}).items():
        if provider not in ADDED_SOURCES or not isinstance(info,dict):continue
        row=records.get(provider)
        if row is None:continue
        row.update(status=str(info.get('status','not_reported'))[:70],
                   reason=str(info.get('reason',''))[:160],
                   attempted=bool(info.get('attempted',False)),
                   fields=[x for x in info.get('fields',[]) if x in SIX_FIELDS])
    return {'version':2 if extended_status is not None else 1,'sources':records}
