#!/usr/bin/env python3
"""
Descarga boletines de Neuquén (Martes y Viernes).

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

import datetime
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://boficial.neuquen.gov.ar/Boletin"


class DescargadorNeuquen(BaseDescargador):
    NOMBRE = "NEUQUÉN"
    DIRECTORIO = "pendientes/neuquen"
    DIAS_VALIDOS = [1, 4]  # Martes, Viernes

    def descargar_fecha(self, fecha, directorio):
        fecha_hasta = fecha + datetime.timedelta(days=1)
        params = {
            "NumeroBusquedaTexto": "",
            "FechaDesde": fecha.strftime("%Y-%m-%d"),
            "FechaHasta": fecha_hasta.strftime("%Y-%m-%d"),
            "TextoBusqueda": "",
        }
        with requests.Session() as session:
            try:
                response = session.get(URL, params=params, verify=False, timeout=30)
                response.raise_for_status()
            except requests.exceptions.RequestException as e:
                print(f"  Error al realizar la búsqueda: {e}")
                return 'error_descarga'

            pdf_url = self._extraer_pdf_url(response.text, fecha)
            if not pdf_url:
                print(f"  No se encontró boletín para esta fecha")
                return 'no_disponible'

            try:
                resp_pdf = session.get(pdf_url, verify=False, 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 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'

    def _extraer_pdf_url(self, html_content, fecha):
        soup = BeautifulSoup(html_content, "html.parser")
        fecha_str = fecha.strftime("%-d/%m/%Y")
        for box in soup.find_all("div", class_="box"):
            texto = box.get_text()
            if "Boletín Oficial" in texto and "Edición Especial" not in texto and fecha_str in texto:
                for link in box.find_all("a", class_="btn-boletin", href=True):
                    if ".pdf" in link["href"].lower():
                        return f"https://boficial.neuquen.gov.ar{link['href']}"
        return None


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