"""Aplicación WSGI para cPanel/Passenger. El rastreo se ejecuta por Cron."""
from __future__ import annotations
import json
import threading
from pathlib import Path
from urllib.parse import parse_qs
import radar_server as radar

ROOT = Path(__file__).resolve().parent
PAGE = ROOT / "Radar.html"

def application(environ, start_response):
    path = environ.get("PATH_INFO", "/") or "/"
    method = environ.get("REQUEST_METHOD", "GET").upper()
    script = environ.get("SCRIPT_NAME", "").rstrip("/")
    request_uri = environ.get("REQUEST_URI", "")
    if path == "/" and script and request_uri and not request_uri.endswith("/"):
        start_response("301 Moved Permanently", [("Location", script + "/"), ("Cache-Control", "no-store")])
        return [b""]
    headers = [("Cache-Control", "no-store"), ("X-Content-Type-Options", "nosniff")]
    if path == "/api/refresh" and method == "POST":
        if not radar.start_manual_refresh():
            body = json.dumps({"ok": False, "message": "Espera un minuto antes de solicitar otra lectura."}).encode("utf-8")
            start_response("429 Too Many Requests", headers + [("Content-Type", "application/json; charset=utf-8")])
            return [body]
        body = json.dumps({"ok": True, "message": "Actualización iniciada"}).encode("utf-8")
        start_response("202 Accepted", headers + [("Content-Type", "application/json; charset=utf-8")])
        return [body]
    if path in ("/", "/Radar.html"):
        try:
            body = PAGE.read_bytes()
        except OSError:
            body = b"No se encontro Radar.html"
            start_response("500 Internal Server Error", headers + [("Content-Type", "text/plain; charset=utf-8")])
            return [body]
        start_response("200 OK", headers + [("Content-Type", "text/html; charset=utf-8")])
        return [body]
    if path == "/api/data":
        try:
            radar.load_state()
            months = int(parse_qs(environ.get("QUERY_STRING", "")).get("months", ["1"])[0])
        except (ValueError, TypeError):
            months = 1
        if months not in (1, 3, 6, 12):
            months = 1
        body = json.dumps(radar.build_response(months), ensure_ascii=False).encode("utf-8")
        start_response("200 OK", headers + [("Content-Type", "application/json; charset=utf-8")])
        return [body]
    body = b"Not found"
    start_response("404 Not Found", headers + [("Content-Type", "text/plain; charset=utf-8")])
    return [body]


