"""Live delay prediction endpoint — runs XGBoost model on user input."""
import sys
from pathlib import Path
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field
from typing import Optional

# predict.py uses relative paths for models/ and data/, so we need to chdir
import os
_PREDICT_DIR = Path(__file__).resolve().parent.parent.parent / "layers" / "predict_delay"
_orig_cwd = os.getcwd()

# Add predict_delay dir to path so we can import predict module
if str(_PREDICT_DIR) not in sys.path:
    sys.path.insert(0, str(_PREDICT_DIR))

os.chdir(_PREDICT_DIR)
from predict import predict_delay, WEATHER_CONDITIONS
os.chdir(_orig_cwd)

router = APIRouter(prefix="/api/predict", tags=["predict"])


class PredictRequest(BaseModel):
    carrier: str = Field(..., description="IATA carrier code, e.g. DL, UA, WN")
    origin: str = Field(..., description="Origin airport IATA code, e.g. ATL")
    dest: str = Field(..., description="Destination airport IATA code, e.g. LAX")
    crs_dep_time: int = Field(..., description="Scheduled departure HHMM, e.g. 1430")
    fl_date: str = Field(..., description="Flight date YYYY-MM-DD")
    weather: Optional[str] = Field(default="Clear", description="Weather condition")



class PredictResponse(BaseModel):
    prediction: str
    delay_probability: float
    confidence: str
    distance_miles: float
    is_holiday_week: bool
    days_to_holiday: int
    is_peak_season: bool
    weather_flag: int
    model_used: str


@router.post("/", response_model=PredictResponse)
def run_prediction(req: PredictRequest):
    """Run the XGBoost model against user-provided flight details."""
    weather_flag = WEATHER_CONDITIONS.get(req.weather, 0)

    saved_cwd = os.getcwd()
    try:
        os.chdir(_PREDICT_DIR)
        result = predict_delay({
            "carrier": req.carrier.upper(),
            "origin": req.origin.upper(),
            "dest": req.dest.upper(),
            "crs_dep_time": req.crs_dep_time,
            "fl_date": req.fl_date,
            "had_weather_delay": weather_flag,
        })
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Prediction failed: {str(e)}")
    finally:
        os.chdir(saved_cwd)

    return PredictResponse(**result)


@router.get("/weather-options")
def get_weather_options():
    """Return available weather conditions for the frontend dropdown."""
    return {"options": list(WEATHER_CONDITIONS.keys())}

# Load route-month weather data once at startup
import pandas as pd
_route_month_csv = _PREDICT_DIR / "data" / "route_month_weather.csv"
_route_month_weather = {}
if _route_month_csv.exists():
    _rmw = pd.read_csv(_route_month_csv)
    for _, row in _rmw.iterrows():
        key = f"{row['route_str']}_{int(row['month'])}"
        _route_month_weather[key] = float(row['weather_delay_rate'])


@router.get("/route-weather")
def get_route_weather(origin: str, dest: str, month: int):
    """Return historical weather delay rate for a route in a given month."""
    key = f"{origin.upper()}_{dest.upper()}_{month}"
    rate = _route_month_weather.get(key)
    if rate is None:
        return {"rate": None, "suggested_weather": "Clear"}
    # Threshold: if >15% of flights had weather delays, suggest adverse
    suggested = "Rain" if rate > 0.15 else "Clear"
    return {"rate": round(rate, 4), "suggested_weather": suggested}

