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

Uso:
    python descargar_chubut.py
    python descargar_chubut.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://boletin.chubut.gov.ar"

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,en;q=0.8",
    "Referer": URL,
}


class DescargadorChubut(BaseDescargador):
    NOMBRE = "CHUBUT"
    DIRECTORIO = "pendientes/chubut"

    def descargar_fecha(self, fecha, directorio):
        fecha_str = fecha.strftime("%Y-%m-%d")
        url_busqueda = f"{URL}/?numero=&fechadesde={fecha_str}&fechahasta={fecha_str}&texto="

        try:
            response = requests.get(url_busqueda, headers=HEADERS, timeout=30)
            response.raise_for_status()
        except requests.exceptions.RequestException as e:
            print(f"  Error al cargar la página de búsqueda: {e}")
            return 'error_descarga'

        soup = BeautifulSoup(response.text, "html.parser")
        table = soup.find("table", class_="table table-striped")
        if not table:
            print(f"  No se encontró tabla de resultados para esta fecha")
            return 'no_disponible'

        enlaces = table.find_all("a", target="_blank")

        # Primero buscar enlace directo al PDF
        for enlace in enlaces:
            texto = enlace.get_text().strip()
            href = enlace.get("href", "")
            if texto and texto != "Ver" and (".pdf" in texto.lower() or ".pdf" in href.lower()):
                pdf_url = href if href.startswith("http") else f"{URL}{href}"
                return self._descargar_pdf(pdf_url, fecha, directorio)

        # Fallback: buscar el botón "Ver" → página de detalle → PDF
        for enlace in enlaces:
            if enlace.get_text().strip() != "Ver":
                continue
            ver_url = enlace.get("href", "")
            if not ver_url.startswith("http"):
                ver_url = f"{URL}{ver_url}"
            try:
                resp_detalle = requests.get(ver_url, headers=HEADERS, timeout=30)
                resp_detalle.raise_for_status()
                soup_detalle = BeautifulSoup(resp_detalle.text, "html.parser")
                boton = soup_detalle.find("a", class_="btn btn-info")
                if boton:
                    pdf_url = boton.get("href", "")
                    if not pdf_url.startswith("http"):
                        pdf_url = f"{URL}{pdf_url}"
                    return self._descargar_pdf(pdf_url, fecha, directorio)
            except requests.exceptions.RequestException as e:
                print(f"  Error al cargar la página de detalle: {e}")
                continue

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

    def _descargar_pdf(self, url, fecha, directorio):
        try:
            response = requests.get(url, headers=HEADERS, 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:
        DescargadorChubut().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)
