#!/usr/bin/env python3
"""Hermes Football: diagnóstico EPG read-only, Python 3.8 compatible."""
import argparse, sqlite3, re, unicodedata, json
from datetime import datetime, timezone

def norm(s):
    s=''.join(c for c in unicodedata.normalize('NFKD',str(s or '').lower()) if not unicodedata.combining(c))
    return re.sub(r'[^a-z0-9]+',' ',s).strip()

def words(s):
    return set(norm(s).split())-{'fc','cf','sc','afc','club','de','the','04'}

def epgtime(s):
    return datetime.strptime(s,'%Y%m%d%H%M%S %z').astimezone(timezone.utc)

def run(football,epg,day):
    a=sqlite3.connect('file:'+football+'?mode=ro',uri=True);a.row_factory=sqlite3.Row
    b=sqlite3.connect('file:'+epg+'?mode=ro',uri=True);b.row_factory=sqlite3.Row
    events=[dict(r) for r in a.execute('SELECT * FROM events WHERE local_day=?',(day,))]
    rows=[dict(r) for r in b.execute('''SELECT canal,titulo,inicio,fin FROM epg_programas WHERE fuente='sling' AND (canal LIKE 'vixpremiumdeportes%' OR canal LIKE 'vixdeportes%') AND inicio < ? AND fin > ?''',((datetime.strptime(day,'%Y-%m-%d').strftime('%Y%m%d')+'235959'),datetime.strptime(day,'%Y-%m-%d').strftime('%Y%m%d')+'000000'))]
    output=[]
    for ev in events:
        teams=[words(ev.get('home')),words(ev.get('away'))]
        try: start=datetime.fromisoformat(ev['starts_utc'].replace('Z','+00:00')).astimezone(timezone.utc)
        except (ValueError,TypeError,AttributeError): start=None
        matches=[]
        for r in rows:
            title=words(r['titulo'])
            if not all(t and len(t & title)>=max(1,len(t)-1) for t in teams):continue
            try: delta=round((epgtime(r['inicio'])-start).total_seconds()/60) if start else None
            except (ValueError,TypeError):delta=None
            matches.append({'canal':r['canal'],'titulo':r['titulo'],'epg_inicio':r['inicio'],'diferencia_minutos':delta,'estado':'REVISAR_HORARIO' if delta is None or abs(delta)>20 else 'COINCIDENCIA_PROPUESTA'})
        output.append({'id':ev.get('id'),'partido':str(ev.get('away'))+' contra '+str(ev.get('home')),'inicio_espn':ev.get('starts_utc'),'coincidencias':matches,'estado':'SIN_COINCIDENCIA' if not matches else ('REVISAR' if len(matches)!=1 or matches[0]['estado']!='COINCIDENCIA_PROPUESTA' else 'PROPUESTA')})
    a.close();b.close()
    print(json.dumps({'modo':'SOLO_LECTURA','fecha':day,'eventos':len(events),'resultados':output},ensure_ascii=False,indent=2))

if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--fecha',required=True);p.add_argument('--football',default='/var/lib/hermes-nexus/football.db');p.add_argument('--epg',default='/var/lib/hermes-nexus/epg.db');x=p.parse_args();run(x.football,x.epg,x.fecha)
