"""SoccerRating logo discovery: independent, conservative, review-first artwork search.

Never changes fixture approval, odds or strategy results. Optional football-data.org
source requires FA_FOOTBALL_DATA_TOKEN. External calls run only on a worker thread.
"""
from __future__ import annotations
import base64, hashlib, io, json, os, re, sqlite3, threading, time, unicodedata
from pathlib import Path
from contextlib import contextmanager, closing
from urllib.parse import quote, urlencode, urlsplit
from urllib.request import Request, build_opener, HTTPRedirectHandler
import sr_fixture_identity as identity  # PHASE4_UNIFIED_IDENTITY

ROOT = Path(__file__).resolve().parent
DB = ROOT / 'soccerrating_logo_review.db'
IMAGES = ROOT / 'soccerrating_logo_candidates'
LOCK = threading.RLock()
WORKER = threading.Lock()
MAX_BYTES = 2 * 1024 * 1024
ALLOWED_HOSTS = {'www.thesportsdb.com','r2.thesportsdb.com', 'api.thesportsdb.com',
                 'www.wikidata.org', 'commons.wikimedia.org', 'upload.wikimedia.org',
                 'api.football-data.org', 'crests.football-data.org',
                 'restcountries.com', 'flags.restcountries.com', 'flagcdn.com', 'flagpedia.net',
                 'site.api.espn.com', 'a.espncdn.com',
                 'v3.football.api-sports.io', 'media.api-sports.io',
                 'flagsapi.com', 'flagscenter.com'}
SOURCES = ('API-Football', 'TheSportsDB', 'ESPN', 'Wikidata')
RETRY_SECONDS = 12*3600
# Small in-memory progress indicator. Logo review DB remains independent of all match data.
PROGRESS = {'checked':0, 'currentTeam':'', 'startedAt':'', 'finishedAt':''}


def _progress(**changes):
    with LOCK: PROGRESS.update(changes)


def norm(s):
    s = unicodedata.normalize('NFKD', str(s or '').casefold())
    return re.sub(r'\s+', ' ', ''.join(c for c in s if not unicodedata.combining(c)).strip())


def ident(name):
    s = re.sub(r'[^a-z0-9]+', ' ', norm(name))
    return ' '.join(x for x in s.split() if x not in {'fc','cf','cd','sc','ac','afc','club','football','soccer','de','the'})


def names_match(a, b):
    a, b = ident(a), ident(b)
    if not a or not b or min(len(a),len(b)) < 4: return False
    # Never silently map a men's club to a women's, reserve or youth team.
    for suffix in ('women','femenino','feminino','ladies','reserves','reserve','u17','u18','u19','u20','u21','u23',' b ',' ii '):
        x = ' ' + ident(a) + ' '; y = ' ' + ident(b) + ' '
        if (suffix in x) != (suffix in y): return False
    return a == b



# FA_AUTOMATIC_CREST_CHAIN_V2: safely broaden discovery ONLY for manual review.
# Exact name + verified source consensus remain necessary for automatic logo saving.
def crest_alias_match(requested, candidate):
    if names_match(requested, candidate):
        return True
    if not isinstance(requested, str) or not isinstance(candidate, str):
        return False
    a, b = ident(requested).split(), ident(candidate).split()
    if not a or not b:
        return False
    protected = {'women','womens','ladies','female','feminine','femenino',
                 'feminino','reserves','reserve','youth','u17','u18','u19',
                 'u20','u21','u23','ii','b'}
    if (set(a) & protected) != (set(b) & protected):
        return False
    # FC, SK, etc. are types of club, not reliable identifiers. Protect
    # against dropping distinctive names or accepting similarly named rivals.
    general = {'sk','fk','fc','sc','ac','cf','losc','osc','football','club'}
    a = [x for x in a if x not in general]
    b = [x for x in b if x not in general]
    def root_token(token):
        # Lyon vs Lyonnais, but only as a manual review candidate.
        if len(token) >= 6 and token.endswith('nais') and len(token[:-4]) >= 4:
            return token[:-4]
        return token
    a = [root_token(x) for x in a]
    b = [root_token(x) for x in b]
    # Exact significant tokens, or differing club word order. Never match by
    # just one common city or an arbitrary string-similarity score.
    return bool(a and b and len(''.join(a)) >= 5 and sorted(a) == sorted(b))


def crest_search_terms(team):
    """At most two conservative discovery variants, never a limitless search."""
    query = str(team or '').strip()
    if not query: return []
    terms = [query]
    significant = [x for x in ident(query).split() if x not in
                   {'sk','fk','fc','cf','sc','ac','osc','losc','club','football'}]
    alternative = ' '.join(significant)
    if len(alternative) >= 5 and norm(alternative) != norm(query):
        terms.append(alternative)
    elif 'lyon' in significant:
        terms.append(query.replace('Lyon','Lyonnais'))
    # A provider can use a shorter city name. Search it only for an
    # Olympique <city> identity, and never auto-approve a short match.
    if len(significant)==2 and significant[0]=='olympique' and len(significant[1])>=4:
        shorter=significant[1]
        if shorter.endswith('nais') and len(shorter)>=8:
            shorter=shorter[:-4]
        terms.append(shorter)
    return list(dict.fromkeys(terms))[:3]


# FA_CREST_SHORT_NAMES_REVIEW_ONLY_V3:
# Many providers list Olympique Lyonnais as just 'Lyon', and similarly use
# short city names for clubs with a distinctive organizational prefix.
# This type of match may be OFFERED FOR HUMAN REVIEW only; it is never
# sufficient to auto-save a logo or count as independent name agreement.
def crest_short_name_match(requested, label, country, provider_country):
    if not (country and provider_country and country_match(country, provider_country)):
        return False
    full=ident(requested).split()
    short=ident(label).split()
    # Common demonyms, e.g. Lyonnais -> Lyon, in team identities.
    if len(full)==2 and full[1].endswith('nais') and len(full[1])>=8:
        full[1]=full[1][:-4]
    # Keep the rule narrow: no bare city matches for Real/Atletico rivals,
    # nor for a club without a known league-country identity.
    if len(full)!=2 or full[0] != 'olympique' or len(short)!=1:
        return False
    if len(short[0]) < 4 or short[0]!=full[1]:
        return False
    return True


def country_match(a, b):
    a,b=norm(a),norm(b)
    equivalents={'usa':'united states', 'united states of america':'united states',
                 'republic of korea':'south korea'}
    return bool(a and b and (a == b or equivalents.get(a)==b or equivalents.get(b)==a))


def key_for(name, country):
    return hashlib.sha256((norm(name)+'|'+norm(country)).encode('utf-8')).hexdigest()[:32]


def setup():
    IMAGES.mkdir(exist_ok=True)
    with LOCK, closing(sqlite3.connect(DB)) as c:
        c.execute('''CREATE TABLE IF NOT EXISTS logo_checks (
            id TEXT PRIMARY KEY, team TEXT NOT NULL, country TEXT NOT NULL DEFAULT '',
            state TEXT NOT NULL, evidence_json TEXT NOT NULL DEFAULT '[]',
            message TEXT NOT NULL DEFAULT '', checked_at INTEGER NOT NULL,
            updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP)''')
        c.execute('CREATE INDEX IF NOT EXISTS idx_logo_state ON logo_checks(state,checked_at)')
        # A conservative rolling 24h quota protects the free API-Football plan
        # even when the user repeatedly restarts the application.
        c.execute('CREATE TABLE IF NOT EXISTS api_football_calls (requested_at INTEGER NOT NULL)')
        c.commit()


@contextmanager
def _db():
    c=sqlite3.connect(DB, timeout=15)
    c.row_factory=sqlite3.Row
    try:yield c
    finally:c.close()


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, request, fp, code, msg, headers, newurl):
        raise ValueError('Redirected image/API URL was refused')


def retrieve(url, *, headers=None, maximum=MAX_BYTES):
    parts=urlsplit(url)
    if parts.scheme!='https' or parts.hostname not in ALLOWED_HOSTS or parts.username or parts.password or parts.port not in (None,443):
        raise ValueError('Untrusted remote logo host')
    req=Request(url, headers={'User-Agent':'FootballAnalyticsLogoDiscovery/1.0 (personal local research)',
                               'Accept':'application/json,image/png,image/jpeg,image/webp,image/gif,*/*;q=.2',
                               **(headers or {})})
    with build_opener(NoRedirect()).open(req, timeout=7) as r:
        if r.status != 200: raise ValueError('HTTP '+str(r.status))
        size=r.headers.get('Content-Length')
        if size and int(size)>maximum: raise ValueError('Remote data too large')
        data=r.read(maximum+1)
        if len(data)>maximum: raise ValueError('Remote data too large')
        return data


def get_json(url, *, headers=None, maximum=650_000):
    return json.loads(retrieve(url, headers=headers, maximum=maximum).decode('utf-8'))



# FA_FOUR_SOURCE_V1: no token is embedded in application files or browser JS.
_AF_CACHE = {}
_AF_CACHE_LOCK = threading.RLock()
_AF_SAFE_DAILY_LIMIT = 75  # published free tier is 100/day; leave a reserve.

def api_football_key():
    return os.environ.get('FA_API_FOOTBALL_KEY','').strip()


def api_football_request(endpoint, params, ttl=3600):
    """Shared server-side API-Football client, cached and quota guarded.

    All API-Sports data is retrieved server-side. Never count it as another
    provider just because multiple endpoints or assets were returned.
    """
    key=api_football_key()
    if not key: return {'response': []}
    if endpoint not in ('fixtures','teams'):
        raise ValueError('API-Football endpoint not supported by importer')
    url='https://v3.football.api-sports.io/'+endpoint+'?'+urlencode(params)
    now=time.time()
    with _AF_CACHE_LOCK:
        cached=_AF_CACHE.get(url)
        if cached and now-cached[0]<ttl:return cached[1]
        with LOCK, _db() as c:
            # Database is owned by the logo scanner, separate from match storage.
            c.execute('CREATE TABLE IF NOT EXISTS api_football_calls (requested_at INTEGER NOT NULL)')
            c.execute('DELETE FROM api_football_calls WHERE requested_at<?',(int(now-86400),))
            used=c.execute('SELECT count(*) FROM api_football_calls').fetchone()[0]
            if used>=_AF_SAFE_DAILY_LIMIT:
                c.commit()
                raise RuntimeError('Free API-Football safety limit reached (75 requests in 24 hours); retry later.')
            recent=c.execute('SELECT COUNT(*) FROM api_football_calls WHERE requested_at>?',(int(now-60),)).fetchone()[0]
            if recent>=8:
                c.commit()
                raise RuntimeError('Free API-Football rate-limit guard reached (8 requests/minute); retry shortly.')
            c.execute('INSERT INTO api_football_calls(requested_at) VALUES(?)',(int(now),))
            c.commit()
        # World-wide fixtures on one day can exceed the 650 KB logo JSON cap.
        payload=get_json(url,headers={'x-apisports-key':key},maximum=5_000_000)
        if not isinstance(payload,dict):raise ValueError('Invalid API-Football response')
        errors=payload.get('errors')
        if errors:
            reason=str(errors)[:180]
            raise ValueError('API-Football: '+reason)
        if not isinstance(payload.get('response'),list):
            raise ValueError('Invalid API-Football response list')
        if len(_AF_CACHE)>120:_AF_CACHE.clear()
        _AF_CACHE[url]=(now,payload)
        return payload


def api_football(team, country=''):
    """The fourth crest source uses a team search, never blindly trusts IDs."""
    if not api_football_key():return []
    payload=api_football_request('teams',{'search':team},ttl=24*3600)
    found=[]
    for x in (payload.get('response') or [])[:20]:
        info=(x.get('team') or {}) if isinstance(x,dict) else {}
        label=str(info.get('name') or '')
        if not crest_alias_match(team,label):continue
        ctry=str(info.get('country') or '')
        if country and ctry and not country_match(country,ctry):continue
        url=str(info.get('logo') or '')
        if urlsplit(url).scheme!='https' or urlsplit(url).hostname!='media.api-sports.io':continue
        found.append({'source':'API-Football','name':label,'country':ctry,
                      'image':url,'sourceId':str(info.get('id') or ''),
                      'license':'Check API-Sports asset usage rights'})
    return found

def sportsdb(team, country=''):
    out=[]
    for query in crest_search_terms(team):
        url='https://www.thesportsdb.com/api/v1/json/123/searchteams.php?'+urlencode({'t':query})
        d=get_json(url)
        for item in (d.get('teams') or [])[:8]:
            if not isinstance(item,dict):continue
            if norm(item.get('strSport')) not in ('soccer','football'):continue
            label=str(item.get('strTeam') or '')
            ctry=str(item.get('strCountry') or '')
            if country and ctry and not country_match(country,ctry):continue
            # Provider aliases are evidence of identity, but not exact votes.
            aliases=re.split(r'[|;,]',str(item.get('strAlternate') or ''))
            strong=crest_alias_match(team,label) or any(crest_alias_match(team,x.strip()) for x in aliases if x.strip())
            short=(not strong and crest_short_name_match(team,label,country,ctry)
                   and 'ligue 1' in norm(item.get('strLeague') or ''))
            if not (strong or short):continue
            if item.get('strBadge'):
                out.append({'source':'TheSportsDB','name':label,
                    'country':ctry, 'image':item['strBadge'],
                    'sourceId':str(item.get('idTeam') or ''), 'license':'Check artwork rights',
                    '_manual_only':not crest_alias_match(team,label)})
        if out: break
    return out


def wikidata(team):
    out=[]
    search=[]
    for query in crest_search_terms(team):
        url='https://www.wikidata.org/w/api.php?'+urlencode({'action':'wbsearchentities','search':query,
             'language':'en','type':'item','limit':8,'format':'json'})
        result=get_json(url)
        search.extend((result.get('search') or [])[:8])
    seen=set()
    for item in search:
        if not isinstance(item,dict) or not crest_alias_match(team,item.get('label')):continue
        if item.get('id') in seen:continue
        seen.add(item.get('id'))
        qid=str(item.get('id') or '')
        if not re.fullmatch(r'Q[1-9]\d*',qid):continue
        entity=get_json('https://www.wikidata.org/wiki/Special:EntityData/'+qid+'.json')
        claims=(entity.get('entities') or {}).get(qid,{}).get('claims') or {}
        # P154 logo image is required; general photo P18 is not a club crest.
        logos=claims.get('P154') or []
        if not logos:continue
        desc=norm(item.get('description'))
        if not any(x in desc for x in ('football','soccer','association football')):
            # Require a club instance when Wikidata description isn't sufficiently specific.
            classes=[str(x.get('mainsnak',{}).get('datavalue',{}).get('value',{}).get('id',''))
                     for x in (claims.get('P31') or [])]
            if 'Q476028' not in classes:continue
        ctry=''
        country_ids=[str(x.get('mainsnak',{}).get('datavalue',{}).get('value',{}).get('id',''))
                     for x in (claims.get('P17') or [])]
        country_ids=[x for x in country_ids if re.fullmatch(r'Q[1-9]\d*',x)]
        if country_ids:
            ent=get_json('https://www.wikidata.org/wiki/Special:EntityData/'+country_ids[0]+'.json')
            ctry=(((ent.get('entities') or {}).get(country_ids[0],{}).get('labels') or {}).get('en') or {}).get('value','')
        filename=logos[0].get('mainsnak',{}).get('datavalue',{}).get('value','')
        if not isinstance(filename,str) or not filename or len(filename)>180:continue
        commons=get_json('https://commons.wikimedia.org/w/api.php?'+urlencode({
            'action':'query','format':'json','titles':'File:'+filename,
            'prop':'imageinfo','iiprop':'url','iiurlwidth':256}))
        pages=(commons.get('query') or {}).get('pages') or {}
        images=[im for page in pages.values() for im in page.get('imageinfo',[])]
        if not images:continue
        pic=images[0].get('thumburl') or images[0].get('url')
        if pic: out.append({'source':'Wikidata','name':item['label'],'country':ctry,
             'image':pic,'sourceId':qid,'license':'See Commons file license'})
    return out


_fd_cache={'at':0,'items':[]}
def football_data(team):
    token=os.environ.get('FA_FOOTBALL_DATA_TOKEN','').strip()
    if not token: return []
    now=time.time()
    if now-_fd_cache['at']>86400:
        # List endpoint supported by football-data.org v4; name-filter server support varies.
        # Cache once per day rather than requesting per fixture.
        res=get_json('https://api.football-data.org/v4/teams?limit=1000',headers={'X-Auth-Token':token})
        _fd_cache.update(at=now,items=(res.get('teams') or [])[:1000])
    return [{'source':'football-data.org','name':x.get('name') or '',
             'country':(x.get('area') or {}).get('name') or '', 'image':re.sub(r'\.svg$', '.png', x['crest'],flags=re.I) if urlsplit(x['crest']).hostname=='crests.football-data.org' else x['crest'],
             'sourceId':str(x.get('id') or ''), 'license':'Check club crest rights'}
            for x in _fd_cache['items'] if isinstance(x,dict) and x.get('crest')
            and (crest_alias_match(team,x.get('name')) or crest_alias_match(team,x.get('shortName')))]



# A third no-token independent crest source: ESPN's team directory. The list is
# competition-specific and only queried when a country is known; no guessing.
_ESPN_CRESTS = {}
_ESPN_COUNTRY_LEAGUES = {
    'japan':('jpn.1','jpn.2'),'england':('eng.1','eng.2'),
    'spain':('esp.1','esp.2'),'italy':('ita.1','ita.2'),
    'germany':('ger.1','ger.2'),'france':('fra.1','fra.2'),
    'scotland':('sco.1',),'portugal':('por.1',),
    'netherlands':('ned.1',),'united states':('usa.1',),
    'brazil':('bra.1',),'argentina':('arg.1',),
    # Verified against public ESPN team directories in Phase12C. Country
    # routing is for artwork discovery ONLY, never fixture source votes.
    'sweden':('swe.1',),'chile':('chi.1',)
}


def espn(team,country=''):
    code=norm(country)
    leagues=_ESPN_COUNTRY_LEAGUES.get(code,())
    found=[]
    for league in leagues:
        cache=_ESPN_CRESTS.get(league)
        if cache is None or time.time()-cache[0]>3600:
            url='https://site.api.espn.com/apis/site/v2/sports/soccer/'+league+'/teams?limit=1000'
            payload=get_json(url)
            sports=payload.get('sports') or []
            entries=[t.get('team') or t for sport in sports for group in sport.get('leagues',[]) for t in group.get('teams',[])]
            _ESPN_CRESTS[league]=(time.time(),entries)
        else:entries=cache[1]
        for x in entries:
            if not isinstance(x,dict):continue
            label=str(x.get('displayName') or '')
            strong=crest_alias_match(team,label) or crest_alias_match(team,x.get('name'))
            short=(not strong and crest_short_name_match(team,label,country,country))
            if not (strong or short):continue
            logos=x.get('logos') or []
            url=logos[0].get('href') if logos and isinstance(logos[0],dict) else ''
            if url and urlsplit(url).hostname=='a.espncdn.com':
                found.append({'source':'ESPN','name':label,'country':country,
                              'image':url,'sourceId':str(x.get('id') or ''),
                              'license':'Check ESPN asset usage rights',
                              '_manual_only':not crest_alias_match(team,label)})
    return found

def rasterize(data):
    from PIL import Image, ImageOps, UnidentifiedImageError
    import warnings
    Image.MAX_IMAGE_PIXELS=4_000_000
    with Image.open(io.BytesIO(data)) as opened:
        opened.verify()
    with Image.open(io.BytesIO(data)) as opened:
        if opened.width*opened.height>4_000_000 or opened.width<20 or opened.height<20:
            raise ValueError('Invalid logo dimensions')
        rgba=opened.convert('RGBA');rgba.thumbnail((320,320))
        canvas=Image.new('RGBA', rgba.size,(255,255,255,0))
        canvas.alpha_composite(rgba)
        save=io.BytesIO();canvas.save(save,format='PNG',optimize=True)
        return save.getvalue()


def fingerprint(png):
    from PIL import Image
    with Image.open(io.BytesIO(png)) as img:
        img=img.convert('RGBA')
        background=Image.new('RGBA',img.size,(255,255,255,255)); background.alpha_composite(img)
        small=background.convert('L').resize((9,8))
        px=list(small.get_flattened_data()) if hasattr(small,"get_flattened_data") else list(small.getdata())
        bits=0
        for y in range(8):
            for x in range(8):bits=(bits<<1) | (1 if px[y*9+x]>px[y*9+x+1] else 0)
        return bits


def same_artwork(a,b):
    # A shape-only dHash can falsely match two different symmetric badges.
    # Compare resized RGB appearance as a second, stricter independent check.
    if (fingerprint(a)^fingerprint(b)).bit_count()>3:
        return False
    from PIL import Image, ImageOps, ImageChops, ImageStat
    colors=[]
    for png in (a,b):
        with Image.open(io.BytesIO(png)) as image:
            rgba=image.convert('RGBA')
            thumb=ImageOps.contain(rgba,(64,64))
            canvas=Image.new('RGBA',(64,64),(255,255,255,255))
            canvas.alpha_composite(thumb,((64-thumb.width)//2,(64-thumb.height)//2))
            colors.append(canvas.convert('RGB'))
    differences=ImageStat.Stat(ImageChops.difference(*colors)).mean
    return max(differences) < 35




# FA_COMMONS_CREST_RECOVERY_V1
# Commons can supplement missing club crest candidates. Files are offered for
# manual review only: Commons may republish the same asset used by Wikidata.
def commons_crest_candidates(team, country=''):
    """Return cautiously matched Wikimedia Commons CREST candidates.

    Filenames must contain all meaningful club tokens and a crest/logo term.
    Never use general club photos, generic images, or unspecific aliases.
    Results cannot be automatic consensus votes.
    """
    target=ident(team).split()
    if not target or len(''.join(target))<4:return []
    results=[];seen=set()
    pages=[]
    for query in crest_search_terms(team):
        url='https://commons.wikimedia.org/w/api.php?'+urlencode({
            'action':'query','generator':'search','gsrsearch':query+' football logo',
            'gsrnamespace':'6','gsrlimit':'15','prop':'imageinfo',
            'iiprop':'url|extmetadata','iiurlwidth':'240','format':'json'})
        data=get_json(url)
        pages.extend(((data.get('query') or {}).get('pages') or {}).values())
    for page in pages:
        title=str(page.get('title') or '')
        if not title.startswith('File:'):continue
        stem=re.sub(r'\.[^.]+$','',title[5:])
        words=ident(stem).split()
        if not any(k in words for k in ('logo','crest','badge','emblem','escudo')):continue
        # The candidate must match the club name itself, not just a country,
        # town, general football photograph or match poster.
        club_tokens=[x for x in words if x not in
                     {'logo','crest','badge','emblem','escudo','football','soccer',
                      'new','vector','transparent','version','svg','png','file'}
                     and not re.fullmatch(r'(?:19|20)\d\d',x)]
        if not crest_alias_match(team,' '.join(club_tokens)):continue
        if any(k in words for k in ('women','ladies','u17','u18','u19','u20','u21','u23','reserves','old','former')):
            continue
        infos=page.get('imageinfo') or []
        if not infos:continue
        info=infos[0]
        meta=info.get('extmetadata') or {}
        license_name=re.sub('<[^>]+>','',str((meta.get('LicenseShortName') or {}).get('value',''))).strip()[:70]
        if not (license_name.startswith(('CC','Public domain','PD','GFDL'))):continue
        link=str(info.get('thumburl') or info.get('url') or '')
        if urlsplit(link).scheme!='https' or urlsplit(link).hostname not in ALLOWED_HOSTS:continue
        if link in seen:continue
        seen.add(link)
        results.append({'source':'Wikimedia Commons (manual)', 'name':team,
                        'country':country,'image':link, 'sourceId':title,
                        'license':license_name+'; check crest trademark rights'})
        if len(results)>=3:break
    return results

def discover(team,country=''):
    """Return reviewed candidates. Network errors never imply source agreement."""
    result=[]; unavailable=[]; ambiguous=False
    # Four named providers maximum. Credential gaps are NOT counted as votes.
    funcs=[('TheSportsDB',sportsdb),('Wikidata',wikidata),('ESPN',espn)]
    if api_football_key(): funcs.insert(0,('API-Football',api_football))
    for source,fn in funcs:
        try:
            if source in ('ESPN','API-Football'):
                detected=country or next((x.get('country') for x in result if x.get('country')),'')
                candidates=fn(team,detected)
            elif source=='TheSportsDB':candidates=fn(team,country)
            else:candidates=fn(team)
            if len(candidates)>1:ambiguous=True
        except Exception as exc:
            # Distinguish unavailable provider from a genuine zero-result response.
            detail = type(exc).__name__
            if hasattr(exc, 'code'): detail += ' HTTP '+str(exc.code)
            unavailable.append(source+': '+detail)
            continue
        for item in candidates[:3]:
            club_identity=identity.crest_identity(team,item['name'])
            if club_identity.classification=='reject':continue
            strict=crest_alias_match(team,item['name'])
            short=bool(item.get('_manual_only') and crest_short_name_match(
                team,item.get('name'),country,item.get('country')))
            if not (strict or short):continue
            if country and item.get('country') and not country_match(country,item.get('country')):
                # A known conflicting country is an identity mismatch.
                continue
            item=dict(item)
            item['_identityReason']=club_identity.reason
            if club_identity.classification=='review':item['_manual_only']=True
            item['_auto_eligible']=bool(not item.get('_manual_only') and
                club_identity.classification in ('exact','normalized','verified_alias') and
                names_match(team,item['name']) and
                (not country or country_match(country,item.get('country'))))
            try: raw=rasterize(retrieve(item['image']))
            except Exception:continue
            if len(raw)>MAX_BYTES:continue
            item=dict(item)
            item['imageData']=raw
            result.append(item)
        # One vote per provider: do not count several results from one site.
    unique={}
    for item in result:
        unique.setdefault(item['source'],item)
    result=list(unique.values())
    # A 3-of-4 clique must agree pairwise on artwork AND club country.
    # Do not use result[0] blindly: it might be the fourth dissenting provider.
    from itertools import combinations
    winning=[]
    for count in range(len(result),2,-1):
        for subset in combinations(result,count):
            if not all(x.get('_auto_eligible') for x in subset):continue
            if not all(same_artwork(a['imageData'],b['imageData'])
                       for a,b in combinations(subset,2)):
                continue
            if not country and (not all(x.get('country') for x in subset) or
                               not all(country_match(subset[0]['country'],x['country']) for x in subset[1:])):
                continue
            winning=list(subset)
            break
        if winning:break
    if len(winning)>=3 and not ambiguous:
        winning_sources={x['source'] for x in winning}
        ordered=winning+[x for x in result if x['source'] not in winning_sources]
        dissent=len(result)-len(winning)
        return 'verified',ordered,(
            f'{len(winning)} of {len(result)} available independent crest sources agree; '
            + (f'{dissent} differing result(s) retained for audit.' if dissent else 'crest matches.')
        )
    # Only if the four-provider verification did not succeed, consult a
    # license-labelled Commons search for ADDITIONAL MANUAL options.
    # Wikimedia Commons and Wikidata are not independent evidence votes.
    extra_note=''
    try:
        recovery=commons_crest_candidates(team,country)
        existing_hashes={hashlib.sha256(x['imageData']).digest() for x in result}
        for item in recovery:
            try:
                raw=rasterize(retrieve(item['image']))
            except Exception:continue
            digest=hashlib.sha256(raw).digest()
            if digest in existing_hashes:continue
            existing_hashes.add(digest)
            result.append(dict(item, imageData=raw))
        if recovery:extra_note=' Commons candidates are for manual review only.'
    except Exception as exc:
        unavailable.append('Wikimedia Commons: '+type(exc).__name__)
    if result:
        return 'review',result,('Source-backed crest options found; confirm correct club before saving.'+extra_note)
    return 'unresolved',[],('No usable results. '+('; '.join(unavailable) if unavailable else 'Try later.'))[:220]


def official_fixture_crest_choices(team,country,fixtures):
    """Exact audited pending fixture only; candidate research, never auto-save."""
    import sr_official_manual_evidence as official
    routes={}
    for fixture in fixtures:
        rec=official.record_for(fixture)
        if not rec or rec.get('regionType')!='national':continue
        for side in ('home','away'):
            if norm(fixture.get(side))!=norm(team):continue
            item=(rec.get('crestResearch') or {}).get(side)
            if not isinstance(item,dict):continue
            nation=rec.get('competitionRegion')
            if not nation or not country_match(nation,item.get('country')):continue
            if country and not country_match(country,nation):continue
            if fixture.get('country') and not country_match(fixture['country'],nation):continue
            pid=str(item.get('providerId') or '')
            label=str(item.get('providerName') or '')
            profile=urlsplit(str(item.get('profileUrl') or ''))
            official_url=urlsplit(str(item.get('officialTeamUrl') or ''))
            if (item.get('provider')!='TheSportsDB' or not re.fullmatch(r'[0-9]{3,12}',pid)
                or not label or identity.category(team)!=identity.category(label)
                or profile.scheme!='https' or profile.hostname!='www.thesportsdb.com'
                or profile.port not in (None,443) or profile.username or profile.password
                or not re.fullmatch(r'/Team/'+re.escape(pid)+r'-[A-Za-z0-9-]+',profile.path)
                or official_url.scheme!='https' or official_url.hostname!='www.ligaportugal.pt'
                or official_url.port not in (None,443) or official_url.username or official_url.password
                or not re.fullmatch(r'/team/[0-9]+/[A-Za-z0-9.-]+',official_url.path)):
                continue
            routes[(pid,label,nation)]=item
    if len(routes)!=1:return []
    (pid,label,nation),item=next(iter(routes.items()))
    payload=get_json('https://www.thesportsdb.com/api/v1/json/123/lookupteam.php?'+urlencode({'id':pid}))
    rows=payload.get('teams') or []
    if len(rows)!=1 or not isinstance(rows[0],dict):return []
    row=rows[0]
    # Exact provider ID, provider name, country and football sport required.
    if (str(row.get('idTeam'))!=pid or norm(row.get('strTeam'))!=norm(label)
        or not country_match(nation,row.get('strCountry'))
        or norm(row.get('strSport')) not in ('soccer','football')
        or identity.category(row.get('strTeam'))!=identity.category(team)):
        return []
    url=str(row.get('strBadge') or '')
    u=urlsplit(url)
    if u.scheme!='https' or u.hostname not in ('www.thesportsdb.com','r2.thesportsdb.com') or u.port not in (None,443) or u.username or u.password:return []
    raw=rasterize(retrieve(url))
    if len(raw)>MAX_BYTES:return []
    return [{'source':'TheSportsDB (official fixture identity review)','name':label,
             'country':nation,'sourceId':pid,'license':'Check artwork rights; official fixture identity review',
             'image':url,'imageData':raw,'_manual_only':True,'_auto_eligible':False}]


def registry_id_crest_choices(team,country,fixtures):
    """Review-only fallback, using existing shared API quota and registry guards."""
    import team_identity_registry as registry
    routes=set()
    for f in fixtures:
        if f.get('status')!='pending':continue
        route=registry.research_pair_route(f.get('home'),f.get('away'))
        if not route:continue
        nation=route['country']
        if country and not country_match(country,nation):continue
        if f.get('country') and not country_match(f['country'],nation):continue
        for i,side in enumerate(('home','away')):
            if registry.norm(f.get(side))==registry.norm(team):
                routes.add((route['teamIds'][i],route[side],nation))
    if len(routes)!=1 or not api_football_key():return []
    tid,label,nation=next(iter(routes))
    with closing(sqlite3.connect(registry.DB.resolve().as_uri()+'?mode=ro',uri=True,timeout=2)) as c:
        ids=c.execute("SELECT DISTINCT external_id FROM provider_ids WHERE team_id=? AND provider='api_football' AND namespace='team'",(tid,)).fetchall()
        if len(ids)!=1:return []
        pid=str(ids[0][0])
        if not re.fullmatch(r'[0-9]{1,12}',pid):return []
        if c.execute("SELECT count(DISTINCT team_id) FROM provider_ids WHERE provider='api_football' AND namespace='team' AND external_id=?",(pid,)).fetchone()[0]!=1:return []
        for table in ('team_crest_rejections','team_crest_quarantine'):
            if c.execute('SELECT 1 FROM '+table+' WHERE team_id=? OR provider_id=? LIMIT 1',(tid,pid)).fetchone():return []
        if c.execute("SELECT 1 FROM team_crests WHERE team_id=? LIMIT 1",(tid,)).fetchone():return []
    rows=api_football_request('teams',{'id':pid},ttl=24*3600).get('response') or []
    if len(rows)!=1 or not isinstance(rows[0],dict):return []
    obj=rows[0].get('team') or {}
    if str(obj.get('id'))!=pid or registry.norm(obj.get('name'))!=registry.norm(label):return []
    if not country_match(nation,obj.get('country')) or obj.get('national') is not False:return []
    if identity.category(obj.get('name'))!=identity.category(team):return []
    url=str(obj.get('logo') or '')
    u=urlsplit(url)
    if (u.scheme!='https' or u.hostname!='media.api-sports.io' or u.port not in (None,443)
        or u.username or u.password or u.query or u.fragment or u.path!='/football/teams/'+pid+'.png'):return []
    # A controller rejection may have been recorded while the provider call ran.
    with closing(sqlite3.connect(registry.DB.resolve().as_uri()+'?mode=ro',uri=True,timeout=2)) as c:
        for table in ('team_crest_rejections','team_crest_quarantine'):
            if c.execute('SELECT 1 FROM '+table+' WHERE team_id=? OR provider_id=? LIMIT 1',(tid,pid)).fetchone():return []
    raw=rasterize(retrieve(url))
    if not raw or len(raw)>MAX_BYTES:return []
    return [{'source':'API-Football (registry identity review)','name':label,'country':nation,
             'sourceId':pid,'license':'Check API-Sports asset usage rights','image':url,
             'imageData':raw,'_manual_only':True,'_auto_eligible':False}]


def _reserve_fixture_crest_review(team,country,fixtures):
    import sr_official_manual_evidence as official
    routes=set()
    for fixture in fixtures:
        route=official.reserve_review_route(fixture)
        if not route or (country and not country_match(country,route["country"])):
            continue
        if norm(fixture.get("away"))==norm(team):
            routes.add((route["away"],route["country"]))
    if len(routes)!=1:return []
    label,nation=next(iter(routes))
    _state, choices, _note=discover(label,nation)
    # Require the exact reserve label AND explicit matching provider country.
    # Even a three-provider agreement for the alternate label remains manual.
    return [dict(item,_manual_only=True,_auto_eligible=False,
                 _identityReason="audited_exact_reserve_fixture_review")
            for item in choices if names_match(label,item.get("name",""))
            and country_match(nation,item.get("country","")) and item.get("imageData")]

def _discover_with_official_review(team,country,fixtures):
    state,candidates,note=discover(team,country)
    if state=='verified' or candidates:return state,candidates,note
    try:
        choices=_reserve_fixture_crest_review(team,country,fixtures)
        if choices:return 'review',choices,'Official reserve-team fixture identity matched; confirm the artwork manually.'
    except Exception as exc:
        note+=' Reserve identity lookup unavailable ('+type(exc).__name__+').'
    try:
        choices=official_fixture_crest_choices(team,country,fixtures)
        if choices:return 'review',choices,'Official fixture identity and exact provider ID matched; confirm artwork manually.'
    except Exception as exc:
        note+=' Official identity lookup unavailable ('+type(exc).__name__+').'
    try:
        choices=registry_id_crest_choices(team,country,fixtures)
        if choices:return 'review',choices,'Registry and exact provider ID/name/country matched; confirm artwork manually.'
    except Exception as exc:
        note+=' Registry identity lookup unavailable ('+type(exc).__name__+').'
    return state,candidates,note


def _store(team,country,state,candidates,message):
    tid=key_for(team,country);safe=[]
    for x in candidates:
        png=x['imageData']
        image_id=hashlib.sha256(png).hexdigest()
        dest=IMAGES/(image_id+'.png')
        if not dest.exists():
            tmp=dest.with_suffix('.tmp');tmp.write_bytes(png);os.replace(tmp,dest)
        safe.append({k:x.get(k,'') for k in ('source','name','country','sourceId','license')}
                    |{'id':image_id,'image':'/logo-review-image/'+image_id+'.png'})
    with LOCK, _db() as c:
        # A human may approve an image while a background lookup is running.
        # Never downgrade the approved review row on a late worker response.
        latest=c.execute('SELECT state FROM logo_checks WHERE id=?',(tid,)).fetchone()
        if latest and latest['state']=='approved' and state!='approved':
            return tid,safe
        c.execute('''INSERT INTO logo_checks(id,team,country,state,evidence_json,message,checked_at)
                     VALUES(?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET
                     state=excluded.state,evidence_json=excluded.evidence_json,
                     message=excluded.message,checked_at=excluded.checked_at,updated_at=CURRENT_TIMESTAMP''',
                  (tid,team,country,state,json.dumps(safe),message,int(time.time())))
        c.commit()
    return tid,safe


def status():
    with LOCK,_db() as c:
        rows=c.execute("SELECT * FROM logo_checks ORDER BY CASE state WHEN 'review' THEN 0 ELSE 1 END,updated_at DESC LIMIT 300").fetchall()
    entries=[{'id':r['id'],'team':r['team'],'country':r['country'],'state':r['state'],
              'message':r['message'],'candidates':json.loads(r['evidence_json'])} for r in rows]
    with LOCK: progress=dict(PROGRESS)
    return {'ok':True,'running':WORKER.locked(),'items':entries,'progress':progress,
            'reviewCount':sum(e['state']=='review' for e in entries),
            'sources':{'API-Football':'enabled (free quota)' if api_football_key() else 'requires FA_API_FOOTBALL_KEY (free)',
                       'TheSportsDB':'enabled','ESPN':'enabled for supported competitions',
                       'Wikidata':'enabled'},
            'requiresPillow':not pillow_ready()}


def pillow_ready():
    try: from PIL import Image;return True
    except ImportError:return False


def image_bytes(image_id):
    if not re.fullmatch(r'[a-f0-9]{64}',image_id):return None
    with LOCK,_db() as c:
        for row in c.execute("SELECT evidence_json FROM logo_checks WHERE state IN ('review','verified','approved')"):
            if any(it.get('id')==image_id for it in json.loads(row[0])):
                p=IMAGES/(image_id+'.png')
                if p.is_file() and p.stat().st_size <= MAX_BYTES:return p.read_bytes()
    return None


def approve(row_id,candidate_id,save_logo,existing_logos):
    if not re.fullmatch(r'[a-f0-9]{32}',str(row_id)) or not re.fullmatch(r'[a-f0-9]{64}',str(candidate_id)):
        raise ValueError('Invalid review selection.')
    with LOCK,_db() as c:
        row=c.execute("SELECT * FROM logo_checks WHERE id=? AND state IN ('review','verified','approved')",(row_id,)).fetchone()
        if not row:raise ValueError('No saved crest candidates are available for this team.')
        candidates=json.loads(row['evidence_json'])
        selected=next((x for x in candidates if x['id']==candidate_id),None)
        if selected is None:raise ValueError('Choose one of the reviewed logos.')
        # Explicit manual reapproval may replace a previously saved team crest.
        # The library save callback backs up the old logo first.
        image=image_bytes(candidate_id)
        if not image:raise ValueError('The reviewed image is unavailable.')
        saved=save_logo(row['team'],'data:image/png;base64,'+base64.b64encode(image).decode('ascii'))
        c.execute("UPDATE logo_checks SET state='approved',message=?,updated_at=CURRENT_TIMESTAMP WHERE id=?",
                  ('Approved manually: '+selected['source'],row_id))
        c.commit()
        return saved



# FA_TARGETED_CREST_RECOVERY_V1: fetch alternative candidates without touching
# the shared team-logo library or any earlier manual approval.
def start_crest_recovery(identifier, side, queue_supplier):
    if not isinstance(identifier,str) or not re.fullmatch(r'sr_[a-f0-9]{24}',identifier):
        raise ValueError('Invalid queue fixture ID.')
    if side not in ('home','away'):raise ValueError('Choose home or away crest.')
    fixture=next((x for x in queue_supplier() if x.get('id')==identifier),None)
    if not fixture:raise ValueError('Fixture no longer awaits approval.')
    team=str(fixture.get(side) or '').strip()
    country=str(fixture.get('country') or '').strip()
    if not country and ',' in str(fixture.get('league') or ''):
        country=str(fixture['league']).split(',',1)[0].strip()
    if not team or len(team)>120:raise ValueError('Invalid team name.')
    if not WORKER.acquire(False):return {'started':False,'running':True}
    def task():
        try:
            _progress(checked=0,currentTeam=team,startedAt=time.strftime('%Y-%m-%d %H:%M:%S'),finishedAt='')
            tid=key_for(team,country)
            with LOCK,_db() as c:
                old=c.execute('SELECT state,evidence_json FROM logo_checks WHERE id=?',(tid,)).fetchone()
            _state, candidates, note=_discover_with_official_review(team,country,[fixture])
            # Retain all previous, source-backed choices for reapproval; don't
            # overwrite a manually saved logo or silently promote new artwork.
            old_candidates=json.loads(old['evidence_json']) if old else []
            known={hashlib.sha256(x['imageData']).hexdigest() for x in candidates}
            for item in old_candidates:
                image_id=item.get('id','')
                if not re.fullmatch(r'[a-f0-9]{64}',image_id):continue
                path=IMAGES/(image_id+'.png')
                if image_id not in known and path.is_file() and path.stat().st_size<=MAX_BYTES:
                    candidates.append({**item, 'imageData':path.read_bytes()})
                    known.add(image_id)
            saved_state='approved' if old and old['state']=='approved' else 'review'
            _store(team,country,saved_state,candidates,
                   'Existing crest unchanged; choose from reviewed source images. '+note)
            _progress(checked=1)
        except Exception as exc:
            _progress(currentTeam=team,checked=0)
            # Diagnostics only, no corruption or logo overwrite on errors.
            try:
                with LOCK,_db() as c:
                    c.execute('UPDATE logo_checks SET message=? WHERE id=?',
                              ('Recovery failed: '+type(exc).__name__,key_for(team,country)))
                    c.commit()
            except Exception:pass
        finally:
            _progress(currentTeam='',finishedAt=time.strftime('%Y-%m-%d %H:%M:%S'))
            WORKER.release()
    try:
        threading.Thread(target=task,daemon=True,name='TargetedCrestRecovery').start()
    except Exception:
        WORKER.release();raise
    return {'started':True,'running':True}

def _team_pairs(matches):
    pairs={}
    for match in matches:
        c=(match.get('country') or '').strip()
        if not c and ',' in str(match.get('league') or ''):
            c=str(match['league']).split(',',1)[0].strip()
        for side in ('home','away'):
            t=str(match.get(side) or '').strip()
            if t and len(t)<=120:pairs[(norm(t),norm(c))]=(t,c)
    return list(pairs.values())


def _retain_review_images(old_row,candidates):
    """Keep validated earlier artwork when a later lookup finds nothing.

    A review image is never a new independent provider vote. The caller
    downgrades combined state to 'review' unless NEW source agreement itself
    is verified. Corrupt/missing/stale disk images are excluded.
    """
    if not old_row or old_row['state'] not in ('review','verified','approved'):
        return list(candidates)
    try:
        old_items=json.loads(old_row['evidence_json'])
    except (TypeError,ValueError):
        return list(candidates)
    if not isinstance(old_items,list):
        return list(candidates)
    result=list(candidates)
    known={hashlib.sha256(x['imageData']).hexdigest()
           for x in result if isinstance(x,dict) and isinstance(x.get('imageData'),bytes)}
    for item in old_items:
        if not isinstance(item,dict):continue
        image_id=item.get('id')
        if not isinstance(image_id,str) or not re.fullmatch(r'[a-f0-9]{64}',image_id):
            continue
        if image_id in known or not item.get('source') or not item.get('name'):
            continue
        p=IMAGES/(image_id+'.png')
        try:
            if not p.is_file() or not (0<p.stat().st_size<=MAX_BYTES):
                continue
            raw=p.read_bytes()
        except OSError:
            continue
        if hashlib.sha256(raw).hexdigest()!=image_id:
            continue
        result.append({**item,'imageData':raw})
        known.add(image_id)
    return result

def _run(queue_supplier,existing_logos,save_logo,force):
    _progress(checked=0,currentTeam='',startedAt=time.strftime('%Y-%m-%d %H:%M:%S'),finishedAt='')
    try:
        fixture_rows=list(queue_supplier())
        pairs=_team_pairs(fixture_rows)
        # Current global logo library keys by team name, not by country.
        # Never silently assign one crest to multiple distinct clubs sharing a name.
        countries_by_name={}
        for t,c in pairs:countries_by_name.setdefault(norm(t),set()).add(norm(c))
        processed=0
        for team,country in pairs:
            if processed>=15:break  # Rate-limit batch; remaining teams can be scanned on next run.
            if norm(team) in existing_logos():continue
            if len(countries_by_name.get(norm(team),()))>1:
                _store(team,country,'unresolved',[],
                       'Same team name appears in multiple countries; cannot safely auto-map by name.')
                continue
            tid=key_for(team,country)
            with LOCK,_db() as c:
                row=c.execute('SELECT state,checked_at,evidence_json FROM logo_checks WHERE id=?',(tid,)).fetchone()
            if row and row['state'] in ('approved','verified'):continue
            # A forced scan MUST revisit unresolved and review items after new
            # sources/credentials become available. Preserve saved approvals.
            if row and not force and int(time.time())-int(row['checked_at'])<RETRY_SECONDS:continue
            processed+=1
            _progress(checked=processed,currentTeam=team)
            try:
                state,candidates,message=_discover_with_official_review(team,country,fixture_rows)
                # Existing valid review evidence must not vanish because a
                # fresh provider call was empty, rate-limited or unavailable.
                # Past candidates NEVER count toward new automatic agreement.
                latest=_retain_review_images(row,candidates)
                # Never mark cross-source consensus when a third source actually disagrees.
                if state=='verified' and candidates and norm(team) not in existing_logos():
                    saved=save_logo(team,'data:image/png;base64,'+
                         base64.b64encode(candidates[0]['imageData']).decode('ascii'))
                    _store(team,country,'verified',latest,message)
                else:
                    retained=len(latest)>len(candidates)
                    _store(team,country,'review' if latest else state,latest,
                           message+(' Previous validated review options retained.' if retained else ''))
            except Exception as exc:
                old_choices=_retain_review_images(row,[])
                _store(team,country,'review' if old_choices else 'unresolved',old_choices,
                       type(exc).__name__+' during lookup; '+
                       ('previous validated review options retained.' if old_choices else 'retry later.'))
            time.sleep(0.25)
    finally:
        _progress(currentTeam='',finishedAt=time.strftime('%Y-%m-%d %H:%M:%S'))
        WORKER.release()


def start_scan(queue_supplier,existing_logos,save_logo,force=False):
    if not pillow_ready():return {'started':False,'error':'Pillow is unavailable in the desktop Python environment.'}
    if not WORKER.acquire(blocking=False):return {'started':False,'running':True}
    try:
        threading.Thread(target=_run,args=(queue_supplier,existing_logos,save_logo,force),daemon=True).start()
        return {'started':True,'running':True}
    except Exception:
        WORKER.release();raise
