#!/usr/bin/env python3
"""
Descarga boletines de Chaco (Lunes, Miércoles y Viernes).

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

import os
import sys
from pathlib import Path

import requests
import urllib3
from bs4 import BeautifulSoup

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

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

URL = "https://boletin.chaco.gob.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",
}


class DescargadorChaco(BaseDescargador):
    NOMBRE = "CHACO"
    DIRECTORIO = "pendientes/chaco"
    DIAS_VALIDOS = [0, 2, 4]  # Lunes, Miércoles, Viernes

    def descargar_fecha(self, fecha, directorio):
        session = requests.Session()
        try:
            session.get(URL, verify=False, timeout=10)
            payload = {
                "bulletin_filter_form[buscar]": "",
                "bulletin_filter_form[createdDate][left_date]": fecha.strftime("%Y-%m-%d"),
                "bulletin_filter_form[createdDate][right_date]": fecha.strftime("%Y-%m-%d"),
                "bulletin_filter_form[nroBulletin]": "",
                "bulletin_filter_form[filter]": "",
            }
            response = session.post(URL, data=payload, verify=False, timeout=30)
            response.raise_for_status()
        except requests.exceptions.Timeout:
            print(f"  Timeout al acceder al sitio")
            return 'error_descarga'
        except requests.RequestException as e:
            print(f"  Error de conexión: {e}")
            return 'error_descarga'

        soup = BeautifulSoup(response.text, "html.parser")
        fecha_display = fecha.strftime("%d/%m/%Y")

        for fila in soup.find_all("tr"):
            td_fecha = fila.find("td", {"data-label": "Fecha de Publicación"})
            if td_fecha and td_fecha.get_text(strip=True) == fecha_display:
                a_tag = fila.find("a", class_="boletin_descarga")
                if a_tag and a_tag.get("href"):
                    return self._descargar_pdf(URL + a_tag["href"], 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, verify=False, 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:
        DescargadorChaco().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)
