#!/usr/bin/env python3
"""
Descarga boletines de Tucumán.

Uso:
    python descargar_tucuman.py
    python descargar_tucuman.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://admin.boletintucuman.gob.ar/Content/Boletin"

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://boletin.tucuman.gov.ar/",
}


class DescargadorTucuman(BaseDescargador):
    NOMBRE = "TUCUMÁN"
    DIRECTORIO = "pendientes/tucuman"

    def descargar_fecha(self, fecha, directorio):
        url = f"{URL_BASE}/{fecha.strftime('%Y_%m_%d')}.pdf"
        try:
            response = requests.get(url, headers=HEADERS, timeout=60)
            if response.status_code == 404:
                print(f"  No disponible (404)")
                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'
        except requests.exceptions.RequestException as e:
            print(f"  Error al descargar: {e}")
            return 'error_descarga'

        try:
            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 Exception as e:
            print(f"  Error al guardar: {e}")
            return 'error_descarga'


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