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

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

import os
import sys
from pathlib import Path
from urllib.parse import urljoin

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://www.boletinoflarioja.com.ar"

_ROOT = Path(__file__).resolve().parent.parent.parent.parent
_DIRECTORIO_DEFAULT = str(_ROOT / "files" / "boletines" / "la_rioja" / "sin_procesar")

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 DescargadorLaRioja(BaseDescargador):
    NOMBRE = "LA RIOJA"
    DIRECTORIO = _DIRECTORIO_DEFAULT

    def descargar_fecha(self, fecha, directorio):
        session = requests.Session()
        session.headers.update(HEADERS)

        url_listado = f"{URL}/boletines_completos.php?anio={fecha.year}"
        try:
            response = session.get(url_listado, verify=False, timeout=10)
            response.raise_for_status()
        except requests.exceptions.RequestException as e:
            print(f"  Error de conexión: {e}")
            return 'error_descarga'

        soup = BeautifulSoup(response.text, "html.parser")
        fecha_compact = fecha.strftime("%d%m%Y")
        fecha_iso = fecha.strftime("%Y-%m-%d")
        fecha_slash = fecha.strftime("%d/%m/%Y")

        for enlace in soup.find_all("a", href=True):
            href = enlace.get("href", "")
            texto = enlace.get_text(strip=True).lower()
            if ".pdf" in href.lower():
                if fecha_compact in href or fecha_iso in href or fecha_slash in texto:
                    return self._descargar_pdf(urljoin(URL, href), fecha, directorio, session)

        url_directa = self._construir_url_directa(fecha, session)
        if url_directa:
            return self._descargar_pdf(url_directa, fecha, directorio, session)

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

    def _construir_url_directa(self, fecha, session):
        patrones = [
            f"{URL}/boletines/{fecha.year}/{fecha.month:02d}/boletin-{fecha.day:02d}-{fecha.month:02d}-{fecha.year}.pdf",
            f"{URL}/pdf/boletin-{fecha.strftime('%d-%m-%Y')}.pdf",
            f"{URL}/boletines/boletin_{fecha.strftime('%Y%m%d')}.pdf",
            f"{URL}/downloads/boletin-{fecha.strftime('%d%m%Y')}.pdf",
            f"{URL}/boletin_{fecha.strftime('%Y-%m-%d')}.pdf",
        ]
        for patron in patrones:
            if self._url_existe(patron, session):
                return patron
        return None

    def _url_existe(self, url, session):
        try:
            response = session.head(url, verify=False, timeout=5, allow_redirects=True)
            return response.status_code == 200
        except Exception:
            return False

    def _descargar_pdf(self, url, fecha, directorio, session):
        try:
            response = session.get(url, verify=False, timeout=30)
            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:
        DescargadorLaRioja().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)
