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

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

import os
import re
import sys
from pathlib import Path

import requests
from bs4 import BeautifulSoup

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

URL_BASE = "https://boletinoficial.lapampa.gob.ar"

MESES_ES = {
    1: "enero", 2: "febrero", 3: "marzo", 4: "abril",
    5: "mayo", 6: "junio", 7: "julio", 8: "agosto",
    9: "septiembre", 10: "octubre", 11: "noviembre", 12: "diciembre",
}

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": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
}


class DescargadorLaPampa(BaseDescargador):
    NOMBRE = "LA PAMPA"
    DIRECTORIO = "pendientes/lapampa"

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

    def descargar_fecha(self, fecha, directorio):
        url_detalle = self._buscar_link_boletin(fecha)
        if not url_detalle:
            print(f"  No se encontró boletín para {fecha}")
            return 'no_disponible'

        pdf_url = self._obtener_pdf_desde_detalle(url_detalle)
        if not pdf_url:
            print(f"  No se encontró PDF en la página de detalle")
            return 'no_disponible'

        try:
            resp = requests.get(pdf_url, headers=HEADERS, timeout=60)
            resp.raise_for_status()
            if "pdf" not in resp.headers.get("Content-Type", "").lower():
                print(f"  Respuesta no es PDF")
                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 _fecha_a_slug(self, fecha):
        return f"{fecha.day}-de-{MESES_ES[fecha.month]}-de-{fecha.year}"

    def _buscar_link_boletin(self, fecha):
        anio_url = f"{URL_BASE}/anio-{fecha.year}.html"
        slug_fecha = self._fecha_a_slug(fecha)
        try:
            resp = requests.get(anio_url, headers=HEADERS, timeout=30)
            resp.raise_for_status()
        except requests.exceptions.RequestException as e:
            print(f"  Error al cargar índice anual: {e}")
            return None

        soup = BeautifulSoup(resp.text, "html.parser")
        for a in soup.find_all("a", href=True):
            href = a["href"]
            if slug_fecha in href and "separata" not in href.lower():
                return URL_BASE + href if href.startswith("/") else href
        for a in soup.find_all("a", href=True):
            href = a["href"]
            if slug_fecha in href:
                return URL_BASE + href if href.startswith("/") else href
        return None

    def _obtener_pdf_desde_detalle(self, url_detalle):
        try:
            resp = requests.get(url_detalle, headers=HEADERS, timeout=30)
            resp.raise_for_status()
        except requests.exceptions.RequestException as e:
            print(f"  Error al cargar página de detalle: {e}")
            return None

        soup = BeautifulSoup(resp.text, "html.parser")
        for a in soup.find_all("a", href=True):
            if re.search(r"BoletinOficial.*BO\d+\.pdf", a["href"], re.IGNORECASE):
                href = a["href"]
                return URL_BASE + href if href.startswith("/") else href
        for a in soup.find_all("a", href=True):
            href = a["href"]
            if "BoletinOficial" in href and href.endswith(".pdf"):
                return URL_BASE + href if href.startswith("/") else href
        return None


if __name__ == "__main__":
    try:
        DescargadorLaPampa().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)
