"""Paprastas FastAPI dashboard tendencijoms peržiūrėti.

Funkcijos:
- /            -> HTML su Chart.js + šalies / trend_type filtras
- /api/countries -> visi įjungti šalys (su trendais per 24h)
- /api/trends    -> ?country=LT&type=daily&limit=50
"""

from __future__ import annotations

import datetime as dt
from pathlib import Path
from typing import Optional

from fastapi import FastAPI, Query
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.templating import Jinja2Templates
from starlette.requests import Request
from sqlalchemy import func, select

from trends_collector.config import Config
from trends_collector.database import Country, DatabaseHandler, Trend


def create_app(cfg: Config, db: DatabaseHandler) -> FastAPI:
    app = FastAPI(title="World Trends Dashboard", version="0.1.0")
    templates_dir = Path(__file__).parent / "templates"
    templates = Jinja2Templates(directory=str(templates_dir))

    @app.get("/", response_class=HTMLResponse)
    async def index(request: Request):
        return templates.TemplateResponse("index.html", {"request": request})

    @app.get("/api/countries")
    async def api_countries():
        since = dt.datetime.utcnow() - dt.timedelta(hours=24)
        with db.session() as s:
            q = (select(Country.iso_code, Country.name_en, Country.name_lt,
                        func.count(Trend.id).label("trend_count"))
                 .join(Trend, Trend.country_id == Country.id, isouter=True)
                 .where((Trend.last_updated >= since) | (Trend.id.is_(None)))
                 .group_by(Country.id, Country.iso_code, Country.name_en, Country.name_lt)
                 .order_by(func.count(Trend.id).desc()))
            rows = s.execute(q).all()
        return [
            {"iso_code": r.iso_code, "name_en": r.name_en,
             "name_lt": r.name_lt, "trend_count": int(r.trend_count or 0)}
            for r in rows
        ]

    @app.get("/api/trends")
    async def api_trends(country: str = Query(...),
                         type: str = Query("daily", regex="^(realtime|hourly|daily)$"),
                         limit: int = Query(50, ge=1, le=500),
                         hours: int = Query(48, ge=1, le=240)):
        c = db.get_country(country.upper())
        if not c:
            return JSONResponse({"error": "country not found"}, status_code=404)
        trends = db.recent_trends(c.id, type, hours=hours, limit=limit)
        return [
            {
                "id": t.id,
                "keyword": t.keyword,
                "category": t.category,
                "language": t.language,
                "score": float(t.score) if t.score is not None else None,
                "volume": t.volume,
                "sentiment": float(t.sentiment) if t.sentiment is not None else None,
                "first_seen": t.first_seen.isoformat() if t.first_seen else None,
                "last_updated": t.last_updated.isoformat() if t.last_updated else None,
                "trend_type": t.trend_type,
                "description": (t.description or "")[:200],
                "url": t.url,
            }
            for t in trends
        ]

    @app.get("/api/stats")
    async def api_stats():
        since = dt.datetime.utcnow() - dt.timedelta(hours=24)
        with db.session() as s:
            total = s.scalar(select(func.count(Trend.id)))
            recent = s.scalar(select(func.count(Trend.id))
                              .where(Trend.last_updated >= since))
            by_cat = s.execute(
                select(Trend.category, func.count(Trend.id))
                .where(Trend.last_updated >= since)
                .group_by(Trend.category)
            ).all()
        return {
            "total_trends": int(total or 0),
            "trends_last_24h": int(recent or 0),
            "by_category": {(c or "unknown"): int(n) for c, n in by_cat},
        }

    return app
