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

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

import os
import re
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_BASE        = "https://boletinoficialsalta.gob.ar"
URL_ANTERIORES  = f"{URL_BASE}/boletin_suplemento_anteriores.php"
URL_REDIRIGIR   = f"{URL_BASE}/Redireccionar_EdicionesNew.php"

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Accept-Language": "es-AR,es;q=0.9",
}


class DescargadorSalta(BaseDescargador):
    NOMBRE = "SALTA"
    DIRECTORIO = "files/boletines/salta/sin_procesar"

    def nombre_archivo(self, fecha):
        return f"SALTA_{fecha.strftime('%Y_%m_%d')}.pdf"

    def descargar_fecha(self, fecha, directorio):
        pdf_url = self._obtener_pdf_url(fecha)
        if pdf_url is None:
            return 'no_disponible'
        if pdf_url is False:
            return 'error_descarga'

        try:
            resp = requests.get(pdf_url, headers=HEADERS, timeout=60)
            resp.raise_for_status()
            if "pdf" not in resp.headers.get("Content-Type", "").lower():
                print(f"  Respuesta no es PDF (Content-Type: {resp.headers.get('Content-Type')})")
                return 'no_disponible'
        except requests.exceptions.RequestException as e:
            print(f"  Error al descargar PDF: {e}")
            return 'error_descarga'

        try:
            archivo_path = os.path.join(directorio, self.nombre_archivo(fecha))
            with open(archivo_path, "wb") as f:
                f.write(resp.content)
            print(f"  Descargado: {archivo_path}")
            return 'ok'
        except Exception as e:
            print(f"  Error al guardar: {e}")
            return 'error_descarga'

    def _obtener_pdf_url(self, fecha):
        """Retorna la URL del PDF, None si no existe, False si hay error de red."""
        fecha_str = fecha.strftime("%d/%m/%Y")
        try:
            resp = requests.post(URL_ANTERIORES, data={"fecha": fecha_str}, headers=HEADERS, timeout=30)
            resp.raise_for_status()
        except requests.exceptions.RequestException as e:
            print(f"  Error al acceder al sitio: {e}")
            return False

        soup = BeautifulSoup(resp.text, "html.parser")

        # Buscar el link al redirector del boletín
        link = soup.find("a", href=re.compile(r"Redireccionar_EdicionesNew\.php"))
        if not link:
            print(f"  No se encontró boletín para esta fecha")
            return None

        try:
            resp2 = requests.get(URL_BASE + "/" + link["href"].lstrip("./"), headers=HEADERS, timeout=30)
            resp2.raise_for_status()
        except requests.exceptions.RequestException as e:
            print(f"  Error al obtener redirect: {e}")
            return False

        # La URL del PDF está en: var pagina="/boletindigital/YYYY/NNNNN.pdf"
        match = re.search(r'var pagina="(/boletindigital/\d{4}/\d+\.pdf)"', resp2.text)
        if not match:
            print(f"  No se encontró URL del PDF")
            return None

        return URL_BASE + match.group(1)


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