#!/usr/bin/env python3
'''V3B: aprobación explícita y UNA comprobación HTTP por enlace.'''
import argparse,json,urllib.request,urllib.error
from urllib.parse import urlsplit
from hermes_football_links_v3 import set_automatic

def approved_url(url):
    p=urlsplit(url)
    return (p.scheme=='http' and p.hostname=='15.204.47.5' and
            p.port==1234 and p.path.startswith('/stream/sling/') and
            not p.username and not p.password)

def check_once(url):
    class NoRedirect(urllib.request.HTTPRedirectHandler):
        def redirect_request(self,*args,**kwargs):
            return None
    request=urllib.request.Request(url,headers={'Range':'bytes=0-2047',
                    'User-Agent':'Hermes-V3B'},method='GET')
    try:
        with urllib.request.build_opener(NoRedirect).open(request,timeout=5) as r:
            data=r.read(2048)
            return 'PLAYLIST_ACCESIBLE' if r.status in (200,206) and (b'#EXTM3U' in data or 'mpegurl' in r.headers.get('Content-Type','').lower()) else 'NO_CONFIRMADO'
    except urllib.error.HTTPError as exc:
        return 'HTTP_'+str(exc.code)
    except Exception:
        return 'NO_CONFIRMADO'

def main():
    p=argparse.ArgumentParser()
    p.add_argument('--propuesta',required=True,help='JSON con evento, EPG, URL Sling y evidencia pública')
    p.add_argument('--aprobar',action='store_true',help='Autorización explícita para guardar')
    a=p.parse_args()
    with open(a.propuesta,encoding='utf-8') as f:
        x=json.load(f)
    url=x.get('url','')
    if not approved_url(url):
        raise SystemExit('RECHAZADO: URL no es Sling del panel autorizado')
    public=x.get('fuente_publica','')
    q=urlsplit(public)
    if q.scheme!='https' or not q.hostname or q.username or q.password:
        raise SystemExit('RECHAZADO: falta URL HTTPS de verificación pública')
    if not x.get('verificado_por','').strip():
        raise SystemExit('RECHAZADO: falta verificador humano de la fuente pública')
    if not a.aprobar:
        print('PREVISUALIZACION SIN ESCRITURA:',x['event_id'])
        print('EPG:',x['epg_canal'],'| PUBLICO:',q.hostname)
        print('Ejecuta --aprobar después de revisar ambas fuentes.')
        return
    evidence={'estado':'CATALOGO_UNICO','epg_canal':x['epg_canal'],
              'diferencia_minutos':x['diferencia_minutos'],
              'fuente_publica':public,'verificado_por':x['verificado_por']}
    result=set_automatic(x['event_id'],url,x['epg_canal'],evidence)
    if not result.get('saved'):
        print('NO ASIGNADO:',result.get('reason'));return
    print('ASIGNADO:',x['event_id'],'| CHEQUEO UNICO:',check_once(url))
    print('PLAYLIST_ACCESIBLE no garantiza video reproducible.')
if __name__=='__main__':
    main()
