#!/usr/bin/env python3
"""
Descarga boletines de Santiago del Estero desde boletinsde.gov.ar.

El sitio requiere un POST con datos personales (ASP.NET WebForms).
Las credenciales se leen del .env raíz del proyecto.

Uso:
    python descargar_sde.py
    python descargar_sde.py --anio 2026 --mes 6 --dia 26
"""

import os
import sys
from pathlib import Path

import requests
import urllib3
from bs4 import BeautifulSoup
from dotenv import load_dotenv

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

sys.path.insert(0, str(Path(__file__).resolve().parent))
from base import BaseDescargador

_ROOT = Path(__file__).resolve().parent.parent.parent.parent
load_dotenv(_ROOT / ".env")

URL = "http://www.boletinsde.gov.ar/"

APELLIDO = os.getenv("SDE_APELLIDO", "")
NOMBRE   = os.getenv("SDE_NOMBRE", "")
DNI      = os.getenv("SDE_DNI", "")
CUIT     = os.getenv("SDE_CUIT", "")

_DIRECTORIO_DEFAULT = str(_ROOT / "files" / "boletines" / "santiago_del_estero" / "sin_procesar")

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Accept-Language": "es-ES,es;q=0.9",
    "Referer": URL,
}


class DescargadorSantiagoDelEstero(BaseDescargador):
    NOMBRE = "SANTIAGO DEL ESTERO"
    DIRECTORIO = _DIRECTORIO_DEFAULT
    DIAS_VALIDOS = [0, 1, 2, 3, 4]

    def descargar_fecha(self, fecha, directorio):
        if not all([APELLIDO, NOMBRE, DNI, CUIT]):
            print("  Error: faltan credenciales SDE_* en el .env")
            return 'error_descarga'

        session = requests.Session()
        session.headers.update(HEADERS)

        try:
            resp = session.get(URL, verify=False, timeout=15)
            resp.raise_for_status()
        except requests.exceptions.RequestException as e:
            print(f"  Error de conexión: {e}")
            return 'error_descarga'

        soup = BeautifulSoup(resp.text, "html.parser")

        def campo(name):
            tag = soup.find("input", {"name": name})
            return tag["value"] if tag else ""

        payload = {
            "__VIEWSTATE": campo("__VIEWSTATE"),
            "__VIEWSTATEGENERATOR": campo("__VIEWSTATEGENERATOR"),
            "__EVENTVALIDATION": campo("__EVENTVALIDATION"),
            "Apellido": APELLIDO,
            "Nombre": NOMBRE,
            "Dni": DNI,
            "Cuit": CUIT,
            "Descarga": "Descargar Boletín",
        }

        try:
            resp_post = session.post(URL, data=payload, verify=False, timeout=30)
            resp_post.raise_for_status()
        except requests.exceptions.RequestException as e:
            print(f"  Error en POST: {e}")
            return 'error_descarga'

        content_type = resp_post.headers.get("Content-Type", "")
        if "pdf" not in content_type.lower() and not resp_post.content.startswith(b"%PDF"):
            print(f"  Respuesta no es PDF (Content-Type: {content_type})")
            return 'no_disponible'

        archivo_path = os.path.join(directorio, self.nombre_archivo(fecha))
        try:
            with open(archivo_path, "wb") as f:
                f.write(resp_post.content)
            print(f"  Descargado: {archivo_path}")
            return 'ok'
        except Exception as e:
            print(f"  Error al guardar: {e}")
            return 'error_descarga'


if __name__ == "__main__":
    try:
        DescargadorSantiagoDelEstero().run()
    except KeyboardInterrupt:
        print("\nDescarga interrumpida por el usuario")
        sys.exit(130)
    except Exception as e:
        print(f"\nError inesperado: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
