#!/usr/bin/env python3
"""
Descarga boletines de Río Negro.

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

import datetime
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.rionegro.gov.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",
}

# ID de la página anual en el CMS de Río Negro (actualizar cuando cambie)
EDICIONES_POR_ANIO = {
    2026: "78963", 2025: "78478", 2024: "77446", 2023: "75524",
    2022: "72537", 2021: "65026", 2020: "56859", 2019: "49132",
    2018: "41830", 2017: "34681", 2016: "27071", 2015: "20070",
}


class DescargadorRioNegro(BaseDescargador):
    NOMBRE = "RÍO NEGRO"
    DIRECTORIO = "files/boletines/rio_negro/sin_procesar"

    def descargar_fecha(self, fecha, directorio):
        if fecha.year not in EDICIONES_POR_ANIO:
            print(f"  Año {fecha.year} no soportado (rango: 2015-2026)")
            return 'no_disponible'

        url_anio = f"{URL}/?contID={EDICIONES_POR_ANIO[fecha.year]}"
        try:
            response = requests.get(url_anio, timeout=30)
            response.raise_for_status()
        except requests.exceptions.RequestException as e:
            print(f"  Error al cargar la página: {e}")
            return 'error_descarga'

        soup = BeautifulSoup(response.text, "html.parser")
        contenedor = soup.find("div", class_="maximoAnchoContiene")
        if not contenedor:
            print(f"  No se encontró el contenedor del año")
            return 'no_disponible'

        id_value = contenedor.get("id", "")
        if "_" not in id_value:
            print(f"  No se pudo extraer el ID del contenedor")
            return 'no_disponible'

        numero = id_value.split("_")[1]
        url_data = f"{URL}/pages/ajax/getBoletinDataJson.php?catid={numero}"

        try:
            data = requests.post(url_data, timeout=30).json()
        except Exception as e:
            print(f"  Error al cargar datos del boletín: {e}")
            return 'error_descarga'

        if not isinstance(data, list) or not data:
            print(f"  Respuesta JSON inválida o vacía")
            return 'no_disponible'

        mes_buscar = MESES_ES[fecha.month].lower()
        for doc_item in data[0].get("documentos", []):
            if doc_item.get("anio", "").lower() != mes_buscar:
                continue
            for elemento in doc_item.get("elementos", []):
                nombre_pdf = elemento.get("nombre", "")
                if "supl" in nombre_pdf.lower():
                    continue
                fecha_str = elemento.get("fecha")
                if not fecha_str:
                    continue
                try:
                    fecha_elem = datetime.date.fromisoformat(fecha_str)
                except ValueError:
                    continue
                if fecha_elem != fecha:
                    continue

                url_pdf = f"{URL}{elemento.get('ruta', '')}{nombre_pdf}"
                try:
                    resp_pdf = requests.get(url_pdf, timeout=60)
                    resp_pdf.raise_for_status()
                    archivo_path = os.path.join(directorio, self.nombre_archivo(fecha))
                    with open(archivo_path, "wb") as f:
                        f.write(resp_pdf.content)
                    print(f"  Descargado: {archivo_path}")
                    return 'ok'
                except Exception as e:
                    print(f"  Error al descargar/guardar el PDF: {e}")
                    return 'error_descarga'

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


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