"""THE OPEN-METEO ADAPTER — a real forecast with no key at all.

Why this file exists
--------------------
The Xweather adapter needs a client id and a client secret, so on a box with no
credential it can only ever report NEEDS KEY. Open-Meteo is free and **keyless**
(no signup, no token, no paid tier), so the demand model keeps a real forecast
without one.

    HTTP 200 + parseable JSON   -> "OK"        real rows, real daily arrays
    any other HTTP status       -> "DEGRADED"  literal "HTTP <code>: <body>" reason
    timeout / DNS / TLS         -> "DEGRADED"  literal "<ExceptionType>: <text>"
    200 but unparseable         -> "DEGRADED"  "HTTP 200 but the body did not parse: ..."

On every non-OK status the result carries ``rows == []``, ``daily == {}`` and
``signals == []`` — the live-data bridge turns that into ZERO claims. A forecast
we could not fetch is reported as unavailable, never guessed.

What is pulled
--------------
One request per capture, for Rochester, NY (43.1566, -77.6088):

    current  temperature_2m, precipitation
    daily    temperature_2m_max, temperature_2m_min, precipitation_sum   (7 days)

Units are requested explicitly (°F, inches) so the thresholds in the signal rules
mean what they say. ``source_url`` is the exact request URL that was called, so
every claim built from this capture cites the call that produced the number.

Signals — same style as the Xweather adapter
--------------------------------------------
    DEMAND DIP   >= 2 consecutive days of zero precipitation forecast
    HEAT SPIKE   a forecast high above 90 °F
    COLD SNAP    a forecast low below 32 °F
"""

from __future__ import annotations

import json
import logging
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone

log = logging.getLogger("jarvis.open_meteo")

COMPONENT_NAME = "OpenMeteoSource"

# ---------------------------------------------------------------------------
# statuses
# ---------------------------------------------------------------------------
OK = "OK"
DEGRADED = "DEGRADED"

STATUS_ORDER = (OK, DEGRADED)

# ---------------------------------------------------------------------------
# endpoint + request shape
# ---------------------------------------------------------------------------
ENDPOINT = "https://api.open-meteo.com/v1/forecast"

USER_AGENT = ("jarvis-open-meteo-source/1.0 (local orchestrator; "
              "+https://github.com/local/jarvis)")

TIMEOUT_SECONDS = 20.0

#: Rochester, NY — the same home base every other live source is counted against.
DEFAULT_LAT = 43.1566
DEFAULT_LON = -77.6088
DEFAULT_LABEL = "Rochester, NY"
DEFAULT_TIMEZONE = "America/New_York"
DEFAULT_DAYS = 7

#: The fields the signal rules need.
DAILY_FIELDS = ("temperature_2m_max", "temperature_2m_min", "precipitation_sum")
CURRENT_FIELDS = ("temperature_2m", "precipitation")
#: Hourly precipitation for the next 48 hours — the storm-window signal.
HOURLY_FIELDS = ("precipitation",)
HOURLY_HOURS = 48

# ---------------------------------------------------------------------------
# signal rules
# ---------------------------------------------------------------------------
DEMAND_DIP = "DEMAND DIP"
HEAT_SPIKE = "HEAT SPIKE"
COLD_SNAP = "COLD SNAP"
#: A single day whose precipitation total clears the heavy-rain threshold.
HEAVY_PRECIP = "HEAVY PRECIP"

#: A day at or below this much precipitation (inches) counts as dry.
DRY_THRESHOLD_IN = 0.0
#: Two dry days in a row is the dip the Xweather rule also uses.
MIN_DRY_RUN_DAYS = 3
#: °F thresholds: above 90 is a heat spike, below 32 is a cold snap.
HEAT_THRESHOLD_F = 90.0
COLD_THRESHOLD_F = 32.0
#: A day at or above this much precipitation (inches) is a heavy-rain day.
HEAVY_PRECIP_IN = 0.5

COLUMNS = ("Date", "High/Low", "Precip")

#: WMO weather codes -> the words the card shows. Reference values only; the
#: number itself is stored in the payload so the wording can never hide it.
WMO_CODES = {
    0: "Clear sky", 1: "Mainly clear", 2: "Partly cloudy", 3: "Overcast",
    45: "Fog", 48: "Depositing rime fog",
    51: "Light drizzle", 53: "Drizzle", 55: "Dense drizzle",
    56: "Freezing drizzle", 57: "Dense freezing drizzle",
    61: "Slight rain", 63: "Rain", 65: "Heavy rain",
    66: "Freezing rain", 67: "Heavy freezing rain",
    71: "Slight snow", 73: "Snow", 75: "Heavy snow", 77: "Snow grains",
    80: "Slight rain showers", 81: "Rain showers", 82: "Violent rain showers",
    85: "Slight snow showers", 86: "Heavy snow showers",
    95: "Thunderstorm", 96: "Thunderstorm with hail", 99: "Thunderstorm with heavy hail",
}


def _now_iso() -> str:
    return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def _snippet(text: str, limit: int = 220) -> str:
    flat = " ".join(str(text or "").split())
    return flat[:limit] + ("…" if len(flat) > limit else "")


def weather_text(code) -> str:
    """The WMO code in words, or the raw code when we do not know it."""
    try:
        number = int(code)
    except (TypeError, ValueError):
        return "—"
    return WMO_CODES.get(number, f"WMO {number}")


def build_url(lat: float = DEFAULT_LAT, lon: float = DEFAULT_LON,
              days: int = DEFAULT_DAYS,
              timezone_name: str = DEFAULT_TIMEZONE) -> str:
    """The exact request URL — and the URL every claim from it cites."""
    params = [
        ("latitude", f"{float(lat):.4f}"),
        ("longitude", f"{float(lon):.4f}"),
        ("daily", ",".join(DAILY_FIELDS)),
        ("hourly", ",".join(HOURLY_FIELDS)),
        ("current", ",".join(CURRENT_FIELDS)),
        ("temperature_unit", "fahrenheit"),
        ("precipitation_unit", "inch"),
        ("timezone", timezone_name),
        ("forecast_days", str(int(days))),
    ]
    return f"{ENDPOINT}?{urllib.parse.urlencode(params)}"


def classify(code: int, text: str = "") -> str:
    """Map a real HTTP response onto one of the two honest statuses."""
    return OK if code == 200 else DEGRADED


# ---------------------------------------------------------------------------
# HTTP
# ---------------------------------------------------------------------------
def _http(url: str) -> tuple[int, str]:
    """One real GET. Returns (status_code, body_text). Raises on network error."""
    req = urllib.request.Request(url, method="GET")
    req.add_header("User-Agent", USER_AGENT)
    req.add_header("Accept", "application/json")
    try:
        with urllib.request.urlopen(req, timeout=TIMEOUT_SECONDS) as resp:
            return resp.status, resp.read(400_000).decode("utf-8", "replace")
    except urllib.error.HTTPError as exc:
        return exc.code, exc.read(20_000).decode("utf-8", "replace")


# ---------------------------------------------------------------------------
# parsing
# ---------------------------------------------------------------------------
def _number(value) -> float | None:
    try:
        if value is None or isinstance(value, bool):
            return None
        return float(value)
    except (TypeError, ValueError):
        return None


def parse_payload(payload: dict) -> tuple[dict, list[list], dict]:
    """Turn an Open-Meteo body into (daily, rows, current).

    ``daily`` keeps the raw arrays (plus the units the API reported) so the signal
    rules read real numbers rather than re-parsing display strings. Anything the
    API did not send stays absent — nothing is filled in.
    """
    if not isinstance(payload, dict):
        raise ValueError("body is not a JSON object")

    daily_raw = payload.get("daily")
    if not isinstance(daily_raw, dict):
        raise ValueError("body carries no 'daily' block")
    times = daily_raw.get("time")
    if not isinstance(times, list) or not times:
        raise ValueError("body carries no daily 'time' array")

    daily = {
        "time": [str(t) for t in times],
        "temperature_2m_max": [_number(v) for v in (daily_raw.get("temperature_2m_max") or [])],
        "temperature_2m_min": [_number(v) for v in (daily_raw.get("temperature_2m_min") or [])],
        "precipitation_sum": [_number(v) for v in (daily_raw.get("precipitation_sum") or [])],
        "units": dict(payload.get("daily_units") or {}),
    }

    hourly_raw = payload.get("hourly") if isinstance(payload.get("hourly"), dict) else {}
    hourly = {
        "time": [str(t) for t in (hourly_raw.get("time") or [])],
        "precipitation": [_number(v) for v in (hourly_raw.get("precipitation") or [])],
        "units": dict(payload.get("hourly_units") or {}),
    }

    current_raw = payload.get("current") if isinstance(payload.get("current"), dict) else {}
    current = {
        "time": str(current_raw.get("time") or ""),
        "temperature_2m": _number(current_raw.get("temperature_2m")),
        "precipitation": _number(current_raw.get("precipitation")),
        "weather_code": current_raw.get("weather_code"),
        "conditions": weather_text(current_raw.get("weather_code")),
        "units": dict(payload.get("current_units") or {}),
    }

    rows = []
    for i, day in enumerate(daily["time"]):
        tmax = daily["temperature_2m_max"][i] if i < len(daily["temperature_2m_max"]) else None
        tmin = daily["temperature_2m_min"][i] if i < len(daily["temperature_2m_min"]) else None
        precip = daily["precipitation_sum"][i] if i < len(daily["precipitation_sum"]) else None
        high_low = (f"{tmax:.1f}°F / {tmin:.1f}°F"
                    if tmax is not None and tmin is not None else "—")
        rows.append([
            day,
            high_low,
            f"{precip:.2f} in" if precip is not None else "—",
        ])
    daily["hourly"] = hourly
    return daily, rows, current


def _at(values, i):
    return values[i] if i < len(values) else None


# ---------------------------------------------------------------------------
# signals
# ---------------------------------------------------------------------------
def _signals(rows=None, columns=None, *, daily: dict | None = None,
             source_url: str = "", label: str = DEFAULT_LABEL) -> list[dict]:
    """Forecast signals, computed from the real daily arrays. Pure, no I/O.

    Returns nothing when the arrays are absent (a refusal, a degraded capture) —
    a rule with no data cannot fire, so a failure can never emit a claim.
    """
    if not isinstance(daily, dict):
        return []
    days = [str(d) for d in (daily.get("time") or [])]
    if not days:
        return []

    tmax = list(daily.get("temperature_2m_max") or [])
    tmin = list(daily.get("temperature_2m_min") or [])
    precip = list(daily.get("precipitation_sum") or [])

    def cited(sig: dict) -> dict:
        if source_url:
            sig["source_url"] = source_url
        sig["label"] = label
        return sig

    out: list[dict] = []

    # -- 1. multi-day zero-precipitation windows ----------------------------
    run: list[str] = []
    runs: list[list[str]] = []
    for i, day in enumerate(days):
        value = _at(precip, i)
        if value is not None and value <= DRY_THRESHOLD_IN:
            run.append(day)
            continue
        if len(run) >= MIN_DRY_RUN_DAYS:
            runs.append(run)
        run = []
    if len(run) >= MIN_DRY_RUN_DAYS:
        runs.append(run)

    for window in runs:
        out.append(cited({
            "kind": DEMAND_DIP,
            "severity": "warn",
            "value": len(window),
            "days": list(window),
            "line": (
                f"DEMAND DIP — {len(window)} consecutive days of zero precipitation "
                f"forecast for {label} ({', '.join(window)}). No storm-driven "
                f"roofing/restoration demand, and dry, settled weather suppresses "
                f"emergency heating calls. Outdoor trades should expect a demand dip."
            ),
        }))

    # -- 2. heat threshold --------------------------------------------------
    for i, day in enumerate(days):
        high = _at(tmax, i)
        if high is None or high <= HEAT_THRESHOLD_F:
            continue
        out.append(cited({
            "kind": HEAT_SPIKE,
            "severity": "warn",
            "value": high,
            "date": day,
            "line": (
                f"HEAT SPIKE — forecast high {high:.1f}°F on {day} for {label}, above "
                f"the {HEAT_THRESHOLD_F:.0f}°F threshold. Cooling demand and no-cool "
                f"calls rise; HVAC capacity should be scheduled before the window lands."
            ),
        }))

    # -- 3. heavy precipitation day -----------------------------------------
    for i, day in enumerate(days):
        total = _at(precip, i)
        if total is None or total < HEAVY_PRECIP_IN:
            continue
        out.append(cited({
            "kind": HEAVY_PRECIP,
            "severity": "warn",
            "value": total,
            "date": day,
            "line": (
                f"HEAVY PRECIP — {total:.2f} in of precipitation forecast on {day} for "
                f"{label}, at or above the {HEAVY_PRECIP_IN:.2f} in threshold. Storm-driven "
                f"roofing, restoration and drainage demand rises; outdoor trades lose the day."
            ),
        }))

    # -- 4. cold threshold --------------------------------------------------
    for i, day in enumerate(days):
        low = _at(tmin, i)
        if low is None or low >= COLD_THRESHOLD_F:
            continue
        out.append(cited({
            "kind": COLD_SNAP,
            "severity": "warn",
            "value": low,
            "date": day,
            "line": (
                f"COLD SNAP — forecast low {low:.1f}°F on {day} for {label}, below the "
                f"{COLD_THRESHOLD_F:.0f}°F threshold. No-heat calls and frozen-pipe "
                f"work rise; heating trades should staff up for the window."
            ),
        }))

    # -- 5. the next 48 hours of hourly precipitation ------------------------
    hourly = daily.get("hourly") if isinstance(daily.get("hourly"), dict) else {}
    hours = [str(t) for t in (hourly.get("time") or [])][:HOURLY_HOURS]
    amounts = list(hourly.get("precipitation") or [])[:HOURLY_HOURS]
    wet = [(h, a) for h, a in zip(hours, amounts) if a is not None and a > 0]
    if wet:
        total_48h = sum(a for _h, a in wet)
        out.append(cited({
            "kind": HEAVY_PRECIP,
            "severity": "info",
            "value": round(total_48h, 2),
            "hours": len(wet),
            "window_hours": len(hours),
            "line": (
                f"HEAVY PRECIP — {total_48h:.2f} in of precipitation forecast across "
                f"{len(wet)} of the next {len(hours)} hours for {label}. Wet hours are "
                f"when emergency roofing, restoration and drainage calls land."
            ),
        }))

    return out


def snapshot(lat: float = DEFAULT_LAT, lon: float = DEFAULT_LON,
             days: int = DEFAULT_DAYS,
             timezone_name: str = DEFAULT_TIMEZONE) -> dict:
    """Fetch the current conditions + 7-day forecast and report what came back.

    Keyless: the only outcomes are OK (real rows) and DEGRADED (literal reason,
    zero rows, zero signals).
    """
    url = build_url(lat, lon, days=days, timezone_name=timezone_name)
    result = {
        "status": DEGRADED,
        "reason": "",
        "http_code": None,
        "rows": [],
        "columns": list(COLUMNS),
        "daily": {},
        "current": {},
        "payload": {},
        "signals": [],
        "source_url": url,
        "endpoint": ENDPOINT,
        "error": "",
        "lat": float(lat),
        "lon": float(lon),
        "days": int(days),
        "timezone": timezone_name,
        "label": DEFAULT_LABEL,
        "generated_at": _now_iso(),
    }

    try:
        code, text = _http(url)
    except Exception as exc:  # timeout, DNS, TLS, connection reset
        result["reason"] = f"{type(exc).__name__}: {exc}"
        result["error"] = result["reason"]
        log.info("open-meteo: DEGRADED — %s", _snippet(result["reason"], 300))
        return result

    result["http_code"] = code
    status = classify(code, text)
    if status != OK:
        result["status"] = DEGRADED
        result["reason"] = f"HTTP {code}: {_snippet(text)}"
        log.info("open-meteo: DEGRADED — %s", _snippet(result["reason"], 300))
        return result

    try:
        payload = json.loads(text)
        daily, rows, current = parse_payload(payload)
    except (TypeError, ValueError) as exc:
        result["status"] = DEGRADED
        result["reason"] = f"HTTP 200 but the body did not parse: {exc}"
        result["error"] = result["reason"]
        log.info("open-meteo: DEGRADED — %s", _snippet(result["reason"], 300))
        return result

    result["status"] = OK
    result["rows"] = rows
    result["daily"] = daily
    result["current"] = current
    result["payload"] = {"daily": daily, "current": current}
    result["signals"] = _signals(rows=rows, columns=COLUMNS, daily=daily,
                                 source_url=url)
    result["reason"] = (
        f"{len(rows)} forecast day(s) for {DEFAULT_LABEL} from Open-Meteo "
        f"(current {current.get('temperature_2m')}°F, "
        f"{current.get('precipitation')} in precipitation)"
    )
    return result
