#!/usr/bin/env python3
"""
Descarga PDFs de secciones Contratos y Convocatorias del Boletín Oficial de Santa Fe.

URL base: https://www.santafe.gob.ar/boletinoficial/
PDF HTML: https://www.santafe.gob.ar/boletinoficial/recursos/boletines/DD-MM-YYYYsectionname.html

Secciones descargadas:
  - contratos      → IX- CONTRATOS, ESTATUTOS, BALANCES, ETC
  - convocatorias  → VIII- CONVOCATORIAS

Uso:
    python3 descargar_santafe.py
    python3 descargar_santafe.py --anio 2016 --mes 3
    python3 descargar_santafe.py --anio 2016 --mes 3 --directorio /ruta/destino
"""

import datetime
import os
import sys
import time
from pathlib import Path

import requests
from weasyprint import HTML as WeasyprintHTML

sys.path.insert(0, str(Path(__file__).resolve().parent))
from dotenv import load_dotenv
load_dotenv()

from base import BaseDescargador, ya_existe_en_provincia


BASE_URL    = "https://www.santafe.gob.ar/boletinoficial"
CONTENT_URL = "https://www.santafe.gob.ar/boletinoficial/recursos/boletines"

SECCIONES = [
    ("contratos",     "CONTRATOS"),
    ("convocatorias", "CONVOCATORIAS"),
]

PDF_STORAGE_PATH = os.getenv('PDF_STORAGE_PATH', '/var/www/html/compartido/boletinesOficiales/pdf')

session = requests.Session()
session.headers.update({
    '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',
    'Referer': 'https://www.santafe.gob.ar/boletinoficial/',
})


def _descargar_seccion(fecha: datetime.date, seccion_url: str, sufijo: str, directorio: str) -> bool:
    anio = fecha.strftime('%Y')
    mes  = fecha.strftime('%m')
    dia  = fecha.strftime('%d')

    nombre_archivo = f"SANTA_FE_{dia}_{mes}_{anio}_{sufijo}.pdf"
    ruta_destino   = os.path.join(directorio, nombre_archivo)

    if ya_existe_en_provincia(directorio, nombre_archivo):
        print(f"    [SKIP] Ya existe: {nombre_archivo}")
        return False

    fecha_url = f"{dia}-{mes}-{anio}"
    url_html  = f"{CONTENT_URL}/{fecha_url}{seccion_url}.html"

    try:
        r = session.get(url_html, timeout=30)

        if r.status_code == 404:
            print(f"    [SKIP] {sufijo}: sección no existe para esta fecha")
            return 'no_disponible'

        if r.status_code != 200:
            print(f"    [SKIP] {sufijo}: HTTP {r.status_code}")
            return 'error_descarga'

        if len(r.text) < 500:
            print(f"    [SKIP] {sufijo}: contenido vacío ({len(r.text)} bytes)")
            return 'no_disponible'

        WeasyprintHTML(string=r.text, base_url=url_html).write_pdf(ruta_destino)

        size_kb = os.path.getsize(ruta_destino) // 1024
        print(f"    [OK]   {nombre_archivo} ({size_kb} KB)")
        return 'ok'

    except Exception as e:
        print(f"    [ERROR] {sufijo} para {fecha}: {e}")
        if os.path.exists(ruta_destino):
            os.remove(ruta_destino)
        return 'error_descarga'


class DescargadorSantaFe(BaseDescargador):
    NOMBRE     = "SANTA FE"
    DIRECTORIO = os.path.join(PDF_STORAGE_PATH, 'SANTA FE')

    def descargar_fecha(self, fecha: datetime.date, directorio: str) -> str:
        alguno_ok = False
        for seccion_url, sufijo in SECCIONES:
            resultado = _descargar_seccion(fecha, seccion_url, sufijo, directorio)
            if resultado == 'ok':
                alguno_ok = True
            time.sleep(0.5)
        return 'ok' if alguno_ok else 'no_disponible'


if __name__ == "__main__":
    DescargadorSantaFe().run()
