#!/usr/bin/env python3
"""
Descarga boletines de Mendoza.

Uso:
    python descargar_mendoza.py
    python descargar_mendoza.py --anio 2024 --mes 5 --dia 15
"""

import os
import re
import sys
from pathlib import Path

import requests

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

import datetime

API_CURRENT = "https://portalgateway.mendoza.gov.ar/api/boe/current"
API_FIND    = "https://portalgateway.mendoza.gov.ar/api/boe/find"
PDF_BASE    = "https://boe.mendoza.gov.ar/default/public/publico/verpdf"

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
    "Accept": "*/*",
}


class DescargadorMendoza(BaseDescargador):
    NOMBRE = "MENDOZA"
    DIRECTORIO = "pendientes/mendoza"

    def nombre_archivo(self, fecha):
        return f"MENDOZA_{fecha.strftime('%Y_%m_%d')}.pdf"

    def descargar_fecha(self, fecha, directorio):
        numero = self._obtener_numero_boletin(fecha)
        if numero is None:
            return 'no_disponible'
        if numero == '__error__':
            return 'error_descarga'

        try:
            resp = requests.get(f"{PDF_BASE}/{numero}", headers=HEADERS, timeout=60)
            resp.raise_for_status()
            if "pdf" not in resp.headers.get("Content-Type", "").lower():
                print(f"  Respuesta no es PDF (Content-Type: {resp.headers.get('Content-Type')})")
                return 'no_disponible'
        except requests.exceptions.RequestException as e:
            print(f"  Error al descargar PDF: {e}")
            return 'error_descarga'

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

    def _obtener_numero_boletin(self, fecha):
        """Retorna el número de boletín, None si no existe, '__error__' si falla la red."""
        session = requests.Session()
        try:
            if fecha == datetime.date.today():
                resp = session.get(API_CURRENT, headers=HEADERS, timeout=30)
            else:
                resp = session.post(
                    API_FIND,
                    headers={**HEADERS, "Content-Type": "application/x-www-form-urlencoded"},
                    data={"fecha": fecha.strftime("%Y-%m-%d")},
                    timeout=30,
                )
            resp.raise_for_status()
        except requests.exceptions.RequestException as e:
            print(f"  Error al consultar API: {e}")
            return '__error__'

        match = re.search(r'data-boe-nro="(\d+)"', resp.text)
        if not match:
            print(f"  No se encontró boletín para {fecha}")
            return None
        return match.group(1)


if __name__ == "__main__":
    try:
        DescargadorMendoza().run()
    except KeyboardInterrupt:
        print("\n\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)
