#!/usr/bin/env python3
"""
Descarga boletines de Entre Ríos.

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

import os
import sys
from pathlib import Path

import requests

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

URL_BASE = "https://www.entrerios.gov.ar/boletin/calendario/Boletin"

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": "application/pdf,*/*",
    "Referer": "https://www.entrerios.gov.ar/boletin/",
}


class DescargadorEntreRios(BaseDescargador):
    NOMBRE = "ENTRE RÍOS"
    DIRECTORIO = "pendientes/entrerios"

    def descargar_fecha(self, fecha, directorio):
        mes_nombre = MESES_ES[fecha.month]
        fecha_str = f"{fecha.day:02d}-{fecha.month:02d}-{str(fecha.year)[2:]}"
        url = f"{URL_BASE}/{fecha.year}/{mes_nombre}/{fecha_str}.pdf"

        try:
            response = requests.get(url, headers=HEADERS, timeout=60)
            if response.status_code == 404:
                print(f"  No disponible (404): {url}")
                return 'no_disponible'
            response.raise_for_status()

            content_type = response.headers.get("Content-Type", "")
            if "pdf" not in content_type.lower() and response.content[:4] != b"%PDF":
                print(f"  El contenido no es un PDF (Content-Type: {content_type})")
                return 'no_disponible'

            archivo_path = os.path.join(directorio, self.nombre_archivo(fecha))
            with open(archivo_path, "wb") as f:
                f.write(response.content)
            size_kb = len(response.content) // 1024
            print(f"  Descargado: {archivo_path} ({size_kb} KB)")
            return 'ok'
        except requests.exceptions.RequestException as e:
            print(f"  Error al descargar: {e}")
            return 'error_descarga'
        except Exception as e:
            print(f"  Error al guardar el archivo: {e}")
            return 'error_descarga'


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