from __future__ import annotations

from datetime import datetime
from typing import List, Optional

import json

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

from app.db import get_pool

router = APIRouter()


class PublicPriceOut(BaseModel):
    url: str
    model_name: str
    prices: dict
    scraped_at: datetime


@router.get("/prices", response_model=List[PublicPriceOut])
async def get_public_prices(url: Optional[str] = None) -> List[PublicPriceOut]:
    pool = get_pool()
    if url is None:
        rows = await pool.fetch(
            "SELECT DISTINCT ON (url) url, model_name, prices, scraped_at "
            "FROM scrape_results ORDER BY url, scraped_at DESC"
        )
    else:
        rows = await pool.fetch(
            "SELECT url, model_name, prices, scraped_at "
            "FROM scrape_results WHERE url = $1 ORDER BY scraped_at DESC LIMIT 1",
            url,
        )
        if not rows:
            raise HTTPException(status_code=404, detail="No scrape results found for the given URL")

    return [PublicPriceOut(
        url=r["url"],
        model_name=r["model_name"],
        prices=r["prices"] if isinstance(r["prices"], dict) else json.loads(r["prices"]),
        scraped_at=r["scraped_at"],
    ) for r in rows]
