from backend.schemas.alert import EchoWeatherAlert
from datetime import datetime


def parse_time(t: str | None):
    if not t:
        return None
    try:
        return datetime.fromisoformat(t.replace("Z", "+00:00"))
    except Exception:
        return None


def categorize(event: str) -> str:
    e = event.lower()

    if "tornado" in e:
        return "tornado"
    if "flood" in e:
        return "flood"
    if "winter" in e:
        return "winter"
    if "marine" in e:
        return "marine"
    if "thunderstorm" in e:
        return "severe"

    return "unknown"


def tier_map(severity: str, urgency: str, certainty: str) -> str:
    text = f"{severity} {urgency} {certainty}".lower()

    if "tornado emergency" in text:
        return "destructive"
    if "pds" in text:
        return "pds"
    if "severe" in text:
        return "considerable"
    if "extreme" in text:
        return "destructive"

    return "normal"


def enrich(feature: dict) -> EchoWeatherAlert:
    p = feature.get("properties", {})

    area = p.get("areaDesc", "")
    counties = [c.strip() for c in area.split(";") if c.strip()]

    description = p.get("description", "") or ""
    instruction = p.get("instruction", "") or ""

    return EchoWeatherAlert(
        id=p.get("id") or feature.get("id"),
        event=p.get("event", "Unknown Event"),
        category=categorize(p.get("event", "")),
        tier=tier_map(
            p.get("severity", ""),
            p.get("urgency", ""),
            p.get("certainty", "")
        ),

        headline=p.get("headline"),
        description=description,
        instruction=instruction,

        affected_counties=counties,

        effective=parse_time(p.get("effective")),
        expires=parse_time(p.get("expires")),

        radar_indicated="radar" in description.lower(),
        confirmed=(p.get("severity", "").lower() == "observed"),

        source="NWS"
    )
