#!/usr/bin/env python3
"""LMP dry-run only. Reads saved EPG JSON, never calls O11 or modifies Hermes."""
import argparse
import json
import re
import unicodedata
from datetime import datetime, timedelta
from pathlib import Path
from zoneinfo import ZoneInfo

TZ = ZoneInfo('America/Tijuana')
ALIASES = {
    'aguilas': ('aguilas', 'mexicali'), 'naranjeros': ('naranjeros', 'hermosillo'),
    'yaquis': ('yaquis', 'obregon'), 'mayos': ('mayos', 'navojoa'),
    'caneros': ('caneros', 'mochis'), 'algodoneros': ('algodoneros', 'guasave'),
    'tomateros': ('tomateros', 'culiacan'), 'venados': ('venados', 'mazatlan'),
    'charros': ('charros', 'jalisco'), 'jaguares': ('jaguares', 'nayarit', 'tepic'),
}

def normalize(value):
    s = ''.join(c for c in unicodedata.normalize('NFD', str(value).lower()) if unicodedata.category(c) != 'Mn')
    return re.sub(r'[^a-z0-9]', '', s)

def identify(name):
    n = normalize(name)
    hits = [slug for slug, aliases in ALIASES.items() if any(normalize(a) in n for a in aliases)]
    return hits[0] if len(hits) == 1 else None

def parse_time(value):
    if not value:
        return None
    try:
        d = datetime.fromisoformat(str(value).replace('Z', '+00:00'))
        return d.replace(tzinfo=TZ) if d.tzinfo is None else d.astimezone(TZ)
    except ValueError:
        return None

def main():
    p = argparse.ArgumentParser(description='Hermes LMP: simulacion sin red ni cambios a produccion')
    p.add_argument('epg_json', help='Snapshot JSON del EPG previamente obtenido')
    p.add_argument('--state', default='hermes_lmp_sim_state.json', help='Estado local de simulacion')
    p.add_argument('--now', help='Fecha ISO para simular otro instante')
    args = p.parse_args()
    now = parse_time(args.now) if args.now else datetime.now(TZ)
    if now is None:
        p.error('--now no es una fecha ISO valida')
    doc = json.loads(Path(args.epg_json).read_text(encoding='utf-8'))
    response = doc.get('response', {})
    games = [g for key in ('games', 'prevGames', 'nextGames') for g in response.get(key, []) if isinstance(g, dict)]
    state_path = Path(args.state)
    state = json.loads(state_path.read_text(encoding='utf-8')) if state_path.exists() else {}
    if not isinstance(state, dict):
        raise ValueError('Estado de simulacion invalido')
    unique = {}
    for g in games:
        away = identify(g.get('awayTeamShort', ''))
        home = identify(g.get('homeTeamShort', ''))
        start = parse_time(g.get('localFullDate'))
        if not (away and home and away != home and start):
            continue
        key = f'{start.isoformat()}|{min(away,home)}|{max(away,home)}'
        unique[key] = (g, away, home, start)
    print('=== HERMES LMP: SIMULACION, SIN PETICIONES A O11 ===')
    print('Hora de evaluacion:', now.isoformat())
    print('Partidos identificados:', len(unique), '/', len(games))
    for key, (g, away, home, start) in sorted(unique.items(), key=lambda x: x[1][3]):
        code = g.get('gameStatus')
        entry = state.setdefault(key, {})
        if code == 2 and 'first_post_seen' not in entry:
            entry['first_post_seen'] = now.isoformat()
        first_post = parse_time(entry.get('first_post_seen'))
        if code == 2 and first_post:
            action = 'SIMULAR CIERRE' if now >= first_post + timedelta(minutes=30) else 'MARGEN POSTPARTIDO'
        elif code == 1:
            action = 'MANTENER ACCESO (EN VIVO)'
        elif code == 0 and start - timedelta(minutes=10) <= now < start:
            action = 'SIMULAR channelsupdaterequest + channelsupdateapply (UNA VEZ POR JUEGO)'
        elif code == 0 and now < start - timedelta(minutes=10):
            action = 'ACCESO PREVIO CERRADO (SIMULADO)'
        else:
            action = 'REVISION MANUAL: ESTADO NO CONCLUYENTE'
        print(f'{away} vs {home} | {start.isoformat()} | EPG={code} | {action}')
    state_path.write_text(json.dumps(state, indent=2, ensure_ascii=False), encoding='utf-8')
    print('Estado de simulacion:', state_path)
    print('PRODUCCION: SIN CAMBIOS | O11: CERO PETICIONES')

if __name__ == '__main__':
    main()
