from __future__ import annotations
from fastapi import FastAPI, HTTPException
from database.manager import DatabaseManager
from agents.analyzer_agent import AnalyzerAgent
from api.openai_client import get_insight
from analytics.metrics import compute_metrics

app = FastAPI(title="Football AI Agents API", version="1.0.0")
db = DatabaseManager()
analyzer = AnalyzerAgent(db)

@app.get("/health")
async def health():
    return {"ok": True}

@app.get("/matches")
async def matches(status: str | None = None, limit: int = 100):
    rows = await db.list_matches(status=status, limit=limit)
    return [{
        "id": r.id,
        "status": r.status,
        "kickoff_ts": r.kickoff_ts,
        "home_team": r.home_team,
        "away_team": r.away_team,
        "minute": r.minute,
        "home_score": r.home_score,
        "away_score": r.away_score,
        "match_url": r.match_url,
        "competition_url": r.competition_url,
        "last_update_ts": r.last_update_ts,
    } for r in rows]

@app.get("/matches/{match_id}")
async def match(match_id: str):
    r = await db.get_match(match_id)
    if not r:
        raise HTTPException(404, "match not found")
    return {
        "id": r.id,
        "status": r.status,
        "kickoff_ts": r.kickoff_ts,
        "home_team": r.home_team,
        "away_team": r.away_team,
        "minute": r.minute,
        "home_score": r.home_score,
        "away_score": r.away_score,
        "match_url": r.match_url,
        "competition_url": r.competition_url,
    }

@app.get("/predictions")
async def predictions(limit: int = 200):
    rows = await db.list_predictions(limit=limit)
    return [{
        "match_id": r.match_id,
        "model": r.model,
        "p_home_win": r.p_home_win,
        "p_draw": r.p_draw,
        "p_away_win": r.p_away_win,
        "exp_home_goals": r.exp_home_goals,
        "exp_away_goals": r.exp_away_goals,
        "confidence": r.confidence,
        "created_ts": r.created_ts,
    } for r in rows]

@app.get("/predictions/{match_id}")
async def prediction(match_id: str, model: str = "poisson+form"):
    r = await db.get_prediction_for_match(match_id, model=model)
    if not r:
        raise HTTPException(404, "prediction not found")
    return {
        "match_id": r.match_id,
        "model": r.model,
        "p_home_win": r.p_home_win,
        "p_draw": r.p_draw,
        "p_away_win": r.p_away_win,
        "exp_home_goals": r.exp_home_goals,
        "exp_away_goals": r.exp_away_goals,
        "confidence": r.confidence,
        "created_ts": r.created_ts,
    }

@app.get("/metrics")
async def metrics(model: str = "poisson+form", recompute: bool = False):
    if recompute:
        m = await compute_metrics(db, model=model)
        await db.save_metrics(model=model, n=m["n_matches"], acc=m["accuracy"], brier=m["brier"], logloss=m["logloss"])
    agg = await db.get_metrics(model=model)
    if not agg:
        return {"model": model, "n_matches": 0, "accuracy": 0.0, "brier": 0.0, "logloss": 0.0}
    return {
        "model": agg.model,
        "n_matches": agg.n_matches,
        "accuracy": agg.accuracy,
        "brier": agg.brier,
        "logloss": agg.logloss,
        "updated_ts": agg.updated_ts,
    }

@app.get("/insights/{match_id}")
async def insights(match_id: str):
    m = await db.get_match(match_id)
    if not m:
        raise HTTPException(404, "match not found")
    pred = await db.get_prediction_for_match(match_id, model="poisson+form")
    ctx = {
        "match": {"home": m.home_team, "away": m.away_team, "status": m.status, "minute": m.minute, "score": [m.home_score, m.away_score]},
        "prediction": None if not pred else {
            "p_home_win": pred.p_home_win, "p_draw": pred.p_draw, "p_away_win": pred.p_away_win,
            "exp_home_goals": pred.exp_home_goals, "exp_away_goals": pred.exp_away_goals, "confidence": pred.confidence
        },
        "home_form": await analyzer.team_form(m.home_team, n=5),
        "away_form": await analyzer.team_form(m.away_team, n=5),
        "head_to_head": await analyzer.h2h(m.home_team, m.away_team, limit=8),
    }
    return get_insight(ctx)
