#!/usr/bin/env python3
"""
Descarga boletines de Santa Cruz (Martes y Jueves).

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

import os
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 = "https://boletinoficial.santacruz.gob.ar"

_ROOT = Path(__file__).resolve().parent.parent.parent.parent
_DIRECTORIO_DEFAULT = str(_ROOT / "files" / "boletines" / "santa_cruz" / "sin_procesar")

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/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",
}


class DescargadorSantaCruz(BaseDescargador):
    NOMBRE = "SANTA CRUZ"
    DIRECTORIO = _DIRECTORIO_DEFAULT
    DIAS_VALIDOS = [1, 3]  # Martes, Jueves

    def descargar_fecha(self, fecha, directorio):
        session = requests.Session()
        session.headers.update(HEADERS)

        try:
            response = session.get(f"{URL}/boletines-pdf", timeout=30)
            response.raise_for_status()
        except requests.exceptions.RequestException as e:
            print(f"  Error al cargar categorías: {e}")
            return 'error_descarga'

        soup = BeautifulSoup(response.text, "html.parser")
        mes_nombre = MESES_ES[fecha.month]
        texto_buscar = f"{mes_nombre.capitalize()} {fecha.year}"
        categoria_url = None

        for enlace in soup.find_all("a", href=True):
            href = enlace.get("href", "")
            texto = enlace.get_text(strip=True)
            if texto == texto_buscar or (f"{mes_nombre}-{fecha.year}" in href.lower() and "/category/" in href):
                categoria_url = href
                break

        if not categoria_url:
            print(f"  No se encontró categoría para {texto_buscar}")
            return 'no_disponible'

        if not categoria_url.startswith("http"):
            categoria_url = URL + ("" if categoria_url.startswith("/") else "/") + categoria_url

        try:
            response_mes = session.get(categoria_url, timeout=30)
            response_mes.raise_for_status()
        except requests.exceptions.RequestException as e:
            print(f"  Error al cargar página del mes: {e}")
            return 'error_descarga'

        soup_mes = BeautifulSoup(response_mes.text, "html.parser")
        fecha_en_pdf = fecha.strftime("%d-%m-%Y")

        for boton in soup_mes.find_all("a", class_="btn-success"):
            href = boton.get("href", "")
            if fecha_en_pdf in href and "B.O." in href and "E.E." not in href and "SUP" not in href:
                pdf_url = href.replace("/../", "/")
                if not pdf_url.startswith("http"):
                    pdf_url = URL + pdf_url
                return self._descargar_pdf(pdf_url, fecha, directorio, session)

        print(f"  No se encontró boletín para esta fecha")
        return 'no_disponible'

    def _descargar_pdf(self, url, fecha, directorio, session):
        try:
            response = session.get(url, timeout=60)
            response.raise_for_status()
            archivo_path = os.path.join(directorio, self.nombre_archivo(fecha))
            with open(archivo_path, "wb") as f:
                f.write(response.content)
            print(f"  Descargado: {archivo_path}")
            return 'ok'
        except requests.exceptions.RequestException as e:
            print(f"  Error al descargar el PDF: {e}")
            return 'error_descarga'
        except Exception as e:
            print(f"  Error al guardar el archivo: {e}")
            return 'error_descarga'


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