"""Global football team-name identity registry for the SoccerRating recovery engine.

Offline, stdlib-only and fail-closed. Sources supply claims; they do not earn fixture
votes. A name identifies a team only when exactly one VERIFIED registry identity
supports it in the available country/category context. No fuzzy auto-merges.

This database is separate from football_analytics.db, the SoccerRating queue,
and the existing fixture evidence database.
"""
from __future__ import annotations

import csv
from functools import lru_cache
import gzip
import hashlib
import json
from pathlib import Path
import re
import sqlite3
from contextlib import closing

import sr_fixture_identity as identity

ROOT = Path(__file__).resolve().parent
DB = ROOT / 'team_identity_registry.db'
SOURCES = {
    'Reep': ('https://reep.football/data/', 'free CC0 snapshot; download and import'),
    'OpenFootball Clubs': ('https://github.com/openfootball/clubs', 'free CC0 text datasets'),
    'Wikidata': ('https://www.wikidata.org/', 'free public data/API'),
    'TheSportsDB': ('https://www.thesportsdb.com/docs/api', 'limited free API'),
    'API-Football': ('https://www.api-football.com/', 'limited free API'),
    'football-data.org': ('https://www.football-data.org/', 'restricted free tier'),
    'KickoffAPI': ('https://docs.kickoffapi.com/', 'limited free API'),
    'OpenLigaDB': ('https://www.openligadb.de/', 'free public API'),
    'Sportmonks': ('https://www.sportmonks.com/football-api/free-plan/', 'limited free leagues'),
    'DBpedia': ('https://dbpedia.org/sparql', 'free public query endpoint'),
}


def norm(value):
    return identity.normalized(str(value or ''))


def _country(value):
    s=norm(value)
    return {
        'czech republic':'czechia','usa':'united states',
        'united states of america':'united states','england uk':'england',
        'osterreich austria':'austria','austria osterreich':'austria',
        'germany deutschland':'germany','deutschland germany':'germany',
        'spain espana':'spain','espana spain':'spain',
        'turkiye':'turkey','republic of turkiye':'turkey',
        'republic of ireland':'ireland','macedonia':'north macedonia'
    }.get(s,s)

def _class(name,cat='',gender=''):
    flags=set(identity.category(str(name or '')))
    flags.update(set(norm(cat).split()) & {'women','youth','reserve'})
    if norm(gender) in {'female','women','woman','girls'}:flags.add('women')
    if re.search(r'\(\s*(?:w|women)\s*\)|\b(?:wfc|lfc|ladies)\b',str(name),re.I):flags.add('women')
    if re.search(r'\bu[ -]?(?:1[0-9]|2[0-3])\b',str(name),re.I):flags.add('youth')
    if re.match(r'^(?:ii|iii)\)\s+',str(name),re.I):flags.add('reserve')
    return frozenset(flags)


def _id(source, external_id):
    raw = (source + '\0' + str(external_id)).encode('utf-8')
    return 'gt_' + hashlib.sha256(raw).hexdigest()[:28]


def _text(v, limit=200):
    return re.sub(r'\s+', ' ', str(v or '').strip())[:limit]


def connection(path=DB):
    c = sqlite3.connect(str(path), timeout=20)
    c.row_factory = sqlite3.Row
    c.execute('PRAGMA busy_timeout=20000')
    return c


def setup(path=DB):
    with closing(connection(path)) as c:
        c.executescript('''
        PRAGMA foreign_keys=ON;
        CREATE TABLE IF NOT EXISTS teams (
          team_id TEXT PRIMARY KEY, canonical_name TEXT NOT NULL,
          country TEXT NOT NULL DEFAULT '', country_key TEXT NOT NULL DEFAULT '',
          category TEXT NOT NULL DEFAULT '', gender TEXT NOT NULL DEFAULT '',
          source TEXT NOT NULL, external_id TEXT NOT NULL,
          UNIQUE(source, external_id));
        CREATE TABLE IF NOT EXISTS aliases (
          team_id TEXT NOT NULL REFERENCES teams(team_id),
          alias TEXT NOT NULL, name_key TEXT NOT NULL,
          source TEXT NOT NULL, status TEXT NOT NULL CHECK(status IN ('verified','proposed')),
          language TEXT NOT NULL DEFAULT '',
          PRIMARY KEY(team_id, name_key, source));
        CREATE INDEX IF NOT EXISTS ix_team_aliases_name ON aliases(name_key,status);
        CREATE TABLE IF NOT EXISTS provider_ids (
          provider TEXT NOT NULL, namespace TEXT NOT NULL DEFAULT '',
          external_id TEXT NOT NULL, team_id TEXT NOT NULL REFERENCES teams(team_id),
          PRIMARY KEY(provider,namespace,external_id));
        CREATE TABLE IF NOT EXISTS name_observations (
          source TEXT NOT NULL, record_id TEXT NOT NULL, side TEXT NOT NULL,
          raw_name TEXT NOT NULL, name_key TEXT NOT NULL,
          country TEXT NOT NULL DEFAULT '', league TEXT NOT NULL DEFAULT '',
          PRIMARY KEY(source,record_id,side));
        CREATE INDEX IF NOT EXISTS ix_team_observations_name ON name_observations(name_key);
        CREATE TABLE IF NOT EXISTS identity_reviews (
          review_id INTEGER PRIMARY KEY AUTOINCREMENT, source TEXT NOT NULL,
          external_id TEXT NOT NULL, raw_name TEXT NOT NULL,
          reason TEXT NOT NULL, created_at TEXT DEFAULT CURRENT_TIMESTAMP,
          UNIQUE(source,external_id,raw_name,reason));
        CREATE TABLE IF NOT EXISTS identity_audit (
          audit_id INTEGER PRIMARY KEY AUTOINCREMENT, action TEXT NOT NULL,
          team_id TEXT NOT NULL, details TEXT NOT NULL,
          created_at TEXT DEFAULT CURRENT_TIMESTAMP);
        CREATE TABLE IF NOT EXISTS source_imports (
          import_id INTEGER PRIMARY KEY AUTOINCREMENT, source TEXT NOT NULL,
          imported_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
          added_teams INTEGER NOT NULL, added_aliases INTEGER NOT NULL,
          note TEXT NOT NULL DEFAULT '');
        ''')
        c.commit()


def add_team(c, source, external_id, name, *, country='', category='', gender='', aliases=(), verified=False):
    """A record identity MUST originate from a source identifier, not a name guess.

    Repeated external IDs update aliases only. Conflicting external ID/name
    claims remain visible for review; no destructive canonical overwrite.
    """
    source=_text(source,60);external_id=_text(external_id,250)
    name=_text(name); country=_text(country,100)
    if not source or not external_id or not norm(name):return None
    team_id=_id(source,external_id)
    old=c.execute('SELECT canonical_name,country_key FROM teams WHERE team_id=?',(team_id,)).fetchone()
    if old is None:
        c.execute('INSERT INTO teams(team_id,canonical_name,country,country_key,category,gender,source,external_id) VALUES(?,?,?,?,?,?,?,?)',
                  (team_id,name,country,_country(country),_text(category,35),_text(gender,35),source,external_id))
    elif (norm(old['canonical_name'])!=norm(name) or (old['country_key'] and _country(country) and old['country_key']!=_country(country))):
        c.execute('INSERT OR IGNORE INTO identity_reviews(source,external_id,raw_name,reason) VALUES(?,?,?,?)',
                  (source,external_id,name,'conflicting_canonical_or_country'))
        # A provider name may change; do not automatically rewrite the master identity.
    status='verified' if verified else 'proposed'
    for alias in (name,*aliases):
        alias=_text(alias)
        key=norm(alias)
        if not key:continue
        c.execute('''INSERT INTO aliases(team_id,alias,name_key,source,status)
            VALUES(?,?,?,?,?) ON CONFLICT(team_id,name_key,source) DO UPDATE SET
            status=CASE WHEN aliases.status='verified' THEN 'verified' ELSE excluded.status END''',
            (team_id,alias,key,source,status))
    return team_id


def add_provider_id(c, team_id, provider, external_id, namespace=''):
    provider=_text(provider,80).casefold();external_id=_text(external_id,150)
    namespace=_text(namespace,80).casefold()
    if not team_id or not provider or not external_id:return False
    existing=c.execute('SELECT team_id FROM provider_ids WHERE provider=? AND namespace=? AND external_id=?',
                       (provider,namespace,external_id)).fetchone()
    if existing and existing['team_id']!=team_id:
        c.execute('INSERT OR IGNORE INTO identity_reviews(source,external_id,raw_name,reason) VALUES(?,?,?,?)',
                  (provider,external_id,namespace,'provider_id_conflict'))
        return False
    c.execute('INSERT OR IGNORE INTO provider_ids(provider,namespace,external_id,team_id) VALUES(?,?,?,?)',
              (provider,namespace,external_id,team_id))
    return True


def _lookup_uncached(name_key,country_key,gender_key,category_key,path):
    if not name_key:return None
    with closing(connection(path)) as c:
        rows=c.execute('''SELECT DISTINCT t.team_id,t.source,t.canonical_name,t.country_key,t.category,t.gender
            FROM aliases a JOIN teams t ON t.team_id=a.team_id
            WHERE a.name_key=? AND a.status='verified' LIMIT 101''',(name_key,)).fetchall()
    if not rows or len(rows)>100:return None
    available=[r for r in rows if not country_key or not r['country_key'] or _country(r['country_key'])==country_key]
    requested=_class(name_key,category_key,gender_key)
    if not requested and any(_class(r['canonical_name'],r['category'],r['gender']) for r in available):return None
    suitable=[]
    for r in available:
        if _class(r['canonical_name'],r['category'],r['gender'])!=requested:continue
        g=norm(r['gender'])
        if gender_key:
            want='women' if gender_key in {'female','woman','girls','women'} else gender_key
            actual='women' if g in {'female','woman','girls','women'} else g
            if actual!=want:continue
        suitable.append(r)
    if len({r['team_id'] for r in suitable})!=1:return None
    if country_key and not suitable[0]['country_key'] and len(rows)>1:return None
    # A verified label does not erase competing PROPOSED claims.
    # Without an explicit gender/category cue, a senior name also asserted
    # by a women/youth/reserve team must ABSTAIN rather than misidentify.
    # Different same-source Reep teams with the same name also remain ambiguous.
    # The provider-ID-scoped event resolver can still disambiguate them.
    if not requested and not gender_key:
        chosen=suitable[0]
        with closing(connection(path)) as c:
            claims=c.execute("""SELECT DISTINCT t.team_id,t.source,t.canonical_name,
                                      t.country_key,t.category,t.gender
                 FROM aliases a JOIN teams t ON t.team_id=a.team_id
                WHERE a.name_key=? AND t.team_id<>?
                  AND (?='' OR t.country_key IN (?,''))
                LIMIT 301""",
                (name_key,chosen['team_id'],country_key,country_key)).fetchall()
        if len(claims)>=301:return None
        target_class=_class(chosen['canonical_name'],chosen['category'],chosen['gender'])
        for rival in claims:
            if _class(rival['canonical_name'],rival['category'],rival['gender'])!=target_class:
                return None
            if rival['source']=='Reep' and chosen['source']=='Reep':
                return None
            # Without a known country, another Reep club in another country
            # remains an unresolved name collision, even if only proposed.
            if (not country_key and rival['source']=='Reep' and
                    rival['country_key']!=chosen['country_key']):
                return None
    return suitable[0]['team_id']


@lru_cache(maxsize=15000)
def _lookup_cached(key,country,gender,category,path,mtime):
    return _lookup_uncached(key,country,gender,category,path)


def lookup(name,*,country='',gender='',category='',path=DB):
    p=Path(path)
    if not p.is_file():return None
    try:return _lookup_cached(norm(name),_country(country),norm(gender),norm(category),str(p),p.stat().st_mtime_ns)
    except (sqlite3.DatabaseError,OSError):return None



def provider_event_alias_map(home,away,candidate_home,candidate_away, *,
                             provider,home_id=None,away_id=None,country='',path=DB):
    """Return (alias map, conflict) for explicit provider TEAM IDs.

    This is not blanket alias verification. Only a source event bearing a team
    identifier from the Reep crosswalk can bridge its own documented name to a
    unique, country/category-consistent Reep canonical name in SoccerRating.
    Missing identifiers or unavailable proof do not loosen the old resolver.
    A demonstrable ID contradiction fails closed.
    """
    mapping=alias_map_for_fixture(home,away,candidate_home,candidate_away,
                                  country=country,path=path)
    ckey=_country(country)
    provider=_text(provider,80).casefold()
    if not ckey or not provider or not Path(path).is_file():
        return mapping,False
    with closing(connection(path)) as c:
        for original,seen,external in ((home,candidate_home,home_id),
                                       (away,candidate_away,away_id)):
            if external is None or str(external).strip()=='':
                continue
            eid=_text(external,150)
            row=c.execute("""SELECT t.team_id,t.canonical_name,t.country_key,
                            t.category,t.gender FROM provider_ids p
                       JOIN teams t ON t.team_id=p.team_id
                      WHERE p.provider=? AND p.namespace='team'
                        AND p.external_id=? AND t.source='Reep'""",
                          (provider,eid)).fetchone()
            if not row:continue
            if _country(row['country_key'])!=ckey:
                return mapping,True
            original_key=norm(original)
            seen_key=norm(seen)
            if not original_key or not seen_key:
                return mapping,True
            target_flags=_class(original)
            source_flags=_class(seen)
            actual_flags=_class(row['canonical_name'],row['category'],row['gender'])
            if source_flags!=actual_flags or target_flags!=actual_flags:
                return mapping,True
            # An original Reep alias is usable ONLY when its asserted entity
            # is unique in the independently known country and team category.
            def source_matches(key,source):
                hits=c.execute("""SELECT DISTINCT t.team_id,t.canonical_name,
                        t.category,t.gender FROM aliases a
                        JOIN teams t ON t.team_id=a.team_id
                        WHERE a.name_key=? AND a.source=? AND t.source=?
                          AND t.country_key=? LIMIT 102""",
                        (key,source,source,ckey)).fetchall()
                if len(hits)>100:return None
                return {r['team_id'] for r in hits if
                        _class(r['canonical_name'],r['category'],r['gender'])==actual_flags}
            matching=source_matches(original_key,'Reep')
            if matching is None or len(matching)>1:
                return mapping,True
            if not matching:
                # Cross-source bridge is scoped to THIS provider event. Never
                # permanently merge OpenFootball and Reep identities by names.
                of_ids=source_matches(original_key,'OpenFootball Clubs')
                if of_ids is None or len(of_ids)>1:
                    return mapping,True
                if not of_ids:
                    continue
                of_id=next(iter(of_ids))
                of=c.execute("SELECT canonical_name,category,gender FROM teams WHERE team_id=?",
                             (of_id,)).fetchone()
                if not of or _class(of['canonical_name'],of['category'],of['gender'])!=actual_flags:
                    return mapping,True
                reep_keys={r[0] for r in c.execute(
                    "SELECT name_key FROM aliases WHERE team_id=? AND source='Reep'",
                    (row['team_id'],))}
                open_keys={r[0] for r in c.execute(
                    "SELECT name_key FROM aliases WHERE team_id=? AND source='OpenFootball Clubs'",
                    (of_id,))}
                # Require both canonical labels to be acknowledged by the
                # other dataset, plus TWO unique, distinctive shared aliases.
                if (norm(row['canonical_name']) not in open_keys or
                        norm(of['canonical_name']) not in reep_keys):
                    return mapping,True
                shared=set()
                for key in reep_keys & open_keys:
                    if len(key)<8 or len(key.split())<2:
                        continue
                    if (source_matches(key,'Reep')=={row['team_id']} and
                            source_matches(key,'OpenFootball Clubs')=={of_id}):
                        shared.add(key)
                if len(shared)<2:
                    return mapping,True
                matching={row['team_id']}
            if row['team_id'] not in matching:
                return mapping,True
            # Reject contradictory provider labels. Source name must be asserted
            # by Reep itself, not just in an unknown-provenance alias record.
            claimed=c.execute("""SELECT 1 FROM aliases
                    WHERE team_id=? AND name_key=? AND source='Reep' LIMIT 1""",
                    (row['team_id'],seen_key)).fetchone()
            if not claimed and seen_key!=norm(row['canonical_name']):
                continue
            conflicts=c.execute("""SELECT DISTINCT t.team_id,t.canonical_name,
                       t.category,t.gender FROM aliases a
                       JOIN teams t ON t.team_id=a.team_id
                      WHERE a.name_key=? AND t.country_key=?
                        AND t.source='Reep' LIMIT 101""",
                        (seen_key,ckey)).fetchall()
            if any(r['team_id']!=row['team_id']
                   and _class(r['canonical_name'],r['category'],r['gender'])==actual_flags
                   for r in conflicts):
                return mapping,True
            if any(mapping.get(k) not in (None,row['team_id'])
                   for k in (original_key,seen_key)):
                return mapping,True
            mapping[original_key]=row['team_id']
            mapping[seen_key]=row['team_id']
    return mapping,False

def alias_map_for_fixture(home,away,candidate_home,candidate_away, *, country='', path=DB):
    """Only unambiguous, source-asserted names get canonical identifiers.

    Mapping is restricted to names occurring in THIS fixture, so no global
    ambiguity or expensive full-database scan can change a voting result.
    """
    mapping={}
    for name in (home,away,candidate_home,candidate_away):
        key=norm(name)
        if not key:continue
        tid=lookup(name,country=country,path=path)
        if tid:mapping[key]=tid
    return mapping


def discovery_queries(home,away, *, source='',country='',path=DB):
    """Use at most one alternate source-provenance query; no fuzzy spray."""
    original=(str(home or '').strip(),str(away or '').strip())
    if not Path(path).is_file():return identity.discovery_queries(*original)
    alternates=[]
    with closing(connection(path)) as c:
        for team in original:
            tid=lookup(team,country=country,path=path)
            if not tid:
                alternates.append(identity.discovery_variant(team));continue
            rows=c.execute('''SELECT a.alias, a.source,t.canonical_name FROM aliases a
                JOIN teams t ON t.team_id=a.team_id WHERE a.team_id=? AND a.status='verified'
                ORDER BY CASE WHEN a.source=? THEN 0 ELSE 1 END,
                         CASE WHEN a.name_key=? THEN 2 ELSE 0 END,
                         length(a.alias) DESC LIMIT 16''',(tid,source,norm(team))).fetchall()
            name=next((r['alias'] for r in rows if norm(r['alias'])!=norm(team)),None)
            alternates.append(name or identity.discovery_variant(team))
    alternate=tuple(alternates)
    return (original,) if tuple(map(norm,alternate))==tuple(map(norm,original)) else (original,alternate)


def research_pair_route(home,away,*,path=DB):
    """Exact registry claims for search ONLY. Never an alias approval or vote."""
    p=Path(path)
    if not p.is_file() or not norm(home) or norm(home)==norm(away):return {}
    try:
        with closing(sqlite3.connect(p.resolve().as_uri()+'?mode=ro',uri=True,timeout=2)) as c:
            c.row_factory=sqlite3.Row
            result=[]
            for name in (home,away):
                rows=c.execute("""SELECT DISTINCT t.team_id,t.canonical_name,t.country,t.country_key,t.category,t.gender,t.source
                    FROM aliases a JOIN teams t USING(team_id)
                    WHERE a.name_key=? AND a.status IN ('verified','proposed') LIMIT 101""",(norm(name),)).fetchall()
                if not rows or len(rows)>100:return {}
                countries={_country(r['country_key']) for r in rows}
                if len(countries)!=1 or '' in countries:return {}
                if any(_class(r['canonical_name'],r['category'],r['gender'])!=_class(name) for r in rows):return {}
                canonical={norm(r['canonical_name']) for r in rows}
                if len(canonical)!=1 or '' in canonical:return {}
                anchored=[]
                for r in rows:
                    ids=c.execute("SELECT 1 FROM provider_ids WHERE team_id=? AND provider IN ('api_football','fotmob','sofascore','sportmonks','espn') LIMIT 1",(r['team_id'],)).fetchone()
                    if ids:anchored.append(r)
                if len(anchored)!=1:return {}
                a=anchored[0]
                result.append((a['country'],_country(a['country_key']),a['canonical_name'],a['team_id']))
            h,a=result
            if h[1]!=a[1] or h[3]==a[3] or norm(h[2])==norm(a[2]):return {}
            return {'country':h[0],'home':h[2],'away':a[2],'teamIds':[h[3],a[3]],'reviewOnly':True}
    except (sqlite3.Error,OSError,ValueError,TypeError):return {}


def verified_names(team, *, country='', path=DB, max_count=12):
    tid=lookup(team,country=country,path=path)
    if not tid:return ()
    with closing(connection(path)) as c:
        rows=c.execute('SELECT alias FROM aliases WHERE team_id=? AND status=\'verified\' ORDER BY length(alias) DESC LIMIT ?',
                       (tid,max_count+1)).fetchall()
    return tuple(row['alias'] for row in rows if norm(row['alias'])!=norm(team))[:max_count]


def local_observations(match_db,queue_db=None,path=DB):
    """Initial seed: original user names are observations, NEVER verified merges."""
    setup(path)
    count=0
    with closing(connection(path)) as target:
        for filename,table,source in ((match_db,'matches','historical_match'),(queue_db,'candidates','soccerrating')):
            if not filename or not Path(filename).is_file():continue
            with closing(sqlite3.connect('file:'+str(Path(filename).resolve())+'?mode=ro',uri=True)) as c:
                c.row_factory=sqlite3.Row
                for r in c.execute(f'SELECT id,home,away,country,league FROM {table}'):
                    for side in ('home','away'):
                        name=_text(r[side]); key=norm(name)
                        if not key:continue
                        target.execute('''INSERT OR IGNORE INTO name_observations
                            (source,record_id,side,raw_name,name_key,country,league)
                            VALUES(?,?,?,?,?,?,?)''',
                            (source,str(r['id']),side,name,key,_text(r['country']),_text(r['league'])))
                        count+=1
        target.commit()
    return count


def _source_country_for_file(file,root):
    path=file.relative_to(root)
    return (path.parts[-2] if len(path.parts)>2 else path.stem).replace('-', ' ').title() if len(path.parts)>1 else ''


def import_openfootball(root, *, path=DB):
    """Parse public-domain openfootball/clubs *.txt files with | aliases.

    Never combine separate club rows just because their names resemble each
    other. This is a source assertion of variants within ONE club record.
    """
    root=Path(root);setup(path)
    files=([root] if root.is_file() else sorted(root.rglob('*.txt')))
    count=0;alias_count=0
    with closing(connection(path)) as c:
        for file in files:
            country=_source_country_for_file(file,root) if root.is_dir() else ''
            current_name='';current_id='';current_category=''; aliases=[]; ordinal=0
            def flush():
                nonlocal count,alias_count
                if not current_name:return
                teamid=add_team(c,'OpenFootball Clubs',current_id,current_name,
                                country=country,category=current_category,aliases=aliases,verified=False)
                if teamid:
                    count+=1;alias_count+=len(aliases)
            for text in file.read_text(encoding='utf-8-sig',errors='replace').splitlines()+['']:
                raw=text.strip()
                if raw.startswith('='):
                    flush();current_name='';aliases=[]
                    if raw.startswith('= ') and not file.name.endswith('.clubs.txt'):
                        country=_text(raw[2:],80)
                    continue
                if raw.startswith('|'):
                    if current_name:
                        aliases.extend(v.strip() for v in raw.split('|') if v.strip())
                    continue
                if not raw or raw.startswith('#') or raw.startswith('//') or raw.startswith('>'):
                    continue
                # Only treat unindented club records as independent teams.
                if text[:1].isspace():continue
                flush();aliases=[];ordinal+=1
                reserve=re.match(r'^(?:ii|iii)\)\s+',raw,re.I)
                if reserve:raw=raw[reserve.end():]
                current_category='reserve' if reserve else ''
                parts=raw.split('|')
                current_name=parts[0].split(',',1)[0].strip()
                aliases.extend(v.strip() for v in parts[1:] if v.strip())
                if not current_name or len(current_name)>150:current_name='';continue
                # Stable across source line reordering; same club names in separate
                # files are not silently joined.
                path_key=str(file.relative_to(root)) if root.is_dir() else file.name
                current_id=path_key+'/'+str(ordinal)+'/'+norm(current_name)
            flush()
        c.execute('INSERT INTO source_imports(source,added_teams,added_aliases,note) VALUES(?,?,?,?)',
                  ('OpenFootball Clubs',count,alias_count,str(root)[:200]))
        c.commit()
    _lookup_cached.cache_clear()
    return {'source':'OpenFootball Clubs','records':count,'aliases':alias_count}


def _open_csv(path):
    return gzip.open(path,'rt',encoding='utf-8-sig',newline='') if str(path).endswith('.gz') else open(path,'r',encoding='utf-8-sig',newline='')


def _find_file(root,name):
    return next((file for file in (root/name,root/(name+'.gz'),root/'csv'/name,root/'csv'/(name+'.gz')) if file.is_file()),None)


def import_reep_csv_bundle(root, *, path=DB):
    """Import Reep v1 CSV bundle; no paid hosted API required.

    Reads entities/aliases/bridges/redirects from the official extracted release.
    V0 files are deliberately NOT accepted: their ID space is incompatible.
    """
    root=Path(root); files={k:_find_file(root,k+'.csv') for k in (
        'entities','provider_aliases','overlay_aliases','bridges','redirects')}
    if not files['entities']:raise ValueError('Reep v1 entities.csv[.gz] is required')
    setup(path)
    redirects={}
    if files['redirects']:
        with _open_csv(files['redirects']) as f:
            for r in csv.DictReader(f):
                if r.get('from_id') and r.get('to_id'):redirects[r['from_id']]=r['to_id']
    def survivor(v):
        for _ in range(12):
            if v not in redirects:break
            v=redirects[v]
        return v
    inserted=0; aliases=0; bridges=0
    with closing(connection(path)) as c:
        with _open_csv(files['entities']) as f:
            for row in csv.DictReader(f):
                if str(row.get('entity_type','')).lower() not in ('team','club','national_team'):continue
                rid=survivor(row.get('reep_id',''))
                if not rid or rid!=row.get('reep_id'):continue
                if add_team(c,'Reep',rid,row.get('canonical_name'),country=row.get('country',''),
                            gender=row.get('gender',''),category='',verified=False):inserted+=1
                if inserted%4000==0:c.commit()
        for key in ('provider_aliases','overlay_aliases'):
            if not files[key]:continue
            with _open_csv(files[key]) as f:
                for row in csv.DictReader(f):
                    rid=survivor(row.get('reep_id',''))
                    teamid=_id('Reep',rid)
                    if not c.execute('SELECT 1 FROM teams WHERE team_id=?',(teamid,)).fetchone():continue
                    alias=_text(row.get('alias'))
                    if not norm(alias):continue
                    c.execute('''INSERT INTO aliases(team_id,alias,name_key,source,status,language)
                         VALUES(?,?,?,?,?,?) ON CONFLICT(team_id,name_key,source) DO NOTHING''',
                        (teamid,alias,norm(alias),'Reep', 'proposed',_text(row.get('language') or row.get('lang'),30)))
                    aliases+=1
                    if aliases%10000==0:c.commit()
        if files['bridges']:
            with _open_csv(files['bridges']) as f:
                for row in csv.DictReader(f):
                    tid=_id('Reep',survivor(row.get('reep_id','')))
                    if not c.execute('SELECT 1 FROM teams WHERE team_id=?',(tid,)).fetchone():continue
                    if add_provider_id(c,tid,row.get('provider'),row.get('external_id'),row.get('namespace','')):
                        bridges+=1
                    if bridges%15000==0:c.commit()
        c.execute('INSERT INTO source_imports(source,added_teams,added_aliases,note) VALUES(?,?,?,?)',
                  ('Reep',inserted,aliases,'v1 CSV bundle; provider bridges '+str(bridges)))
        c.commit()
    _lookup_cached.cache_clear()
    return {'source':'Reep','teams':inserted,'aliases':aliases,'provider_ids':bridges}


def import_normalized_csv(filename,source, *, path=DB, verified=False):
    """Import user-reviewed CSV exports from ANY of the 10 free sources.

    Required: external_id,name. Optional country, category, gender, aliases
    (separated by |), provider, namespace. Defaults to PROPOSED because
    unvetted third-party exports do not establish safe cross-provider merges.
    """
    if source not in SOURCES:raise ValueError('Use one of the ten documented source names')
    setup(path)
    count=0;aliases=0
    with closing(connection(path)) as c, _open_csv(filename) as f:
        reader=csv.DictReader(f)
        if not reader.fieldnames or not {'external_id','name'}.issubset(reader.fieldnames):
            raise ValueError('Expected CSV headers external_id,name')
        for row in reader:
            alt=[n.strip() for n in (row.get('aliases') or '').split('|') if n.strip()]
            tid=add_team(c,source,row.get('external_id'),row.get('name'),
                         country=row.get('country',''),category=row.get('category',''),
                         gender=row.get('gender',''),aliases=alt,verified=verified)
            if not tid:continue
            count+=1;aliases+=len(alt)
            if row.get('provider'):
                add_provider_id(c,tid,row['provider'],row.get('external_id'),row.get('namespace',''))
            if count%2000==0:c.commit()
        c.execute('INSERT INTO source_imports(source,added_teams,added_aliases,note) VALUES(?,?,?,?)',
                  (source,count,aliases,'reviewed' if verified else 'unverified export'))
        c.commit()
    _lookup_cached.cache_clear()
    return {'source':source,'records':count,'aliases':aliases,'status':'verified' if verified else 'proposed'}


def stats(path=DB):
    if not Path(path).is_file():return {'ready':False,'sources':len(SOURCES)}
    with closing(connection(path)) as c:
        counts={key:c.execute('SELECT COUNT(*) FROM '+table).fetchone()[0] for key,table in (
            ('teams','teams'),('aliases','aliases'),('verifiedAliases',"aliases WHERE status='verified'"),
            ('observations','name_observations'),('providerIds','provider_ids'),
            ('reviews','identity_reviews'))}
        counts['ambiguousAliases']=c.execute('''SELECT count(*) FROM (SELECT a.name_key FROM aliases a
            JOIN teams t ON t.team_id=a.team_id WHERE a.status='verified'
            GROUP BY a.name_key HAVING count(DISTINCT a.team_id)>1)''').fetchone()[0]
        counts['distinctObservedNames']=c.execute('SELECT count(DISTINCT name_key) FROM name_observations').fetchone()[0]
        counts['sourceImports']=[{'source':r[0],'imports':r[1]} for r in c.execute(
            'SELECT source,count(*) FROM source_imports GROUP BY source ORDER BY source')]
        return {'ready':True,'catalogSources':len(SOURCES),**counts}
