"""Art-DAG oEmbed endpoint.

Returns oEmbed JSON responses for Art-DAG content (media, recipes, effects, runs).
"""

import os

from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse

router = APIRouter()


@router.get("/oembed")
async def oembed(request: Request):
    url = request.query_params.get("url", "")
    if not url:
        return JSONResponse({"error": "url parameter required"}, status_code=400)

    # Parse URL to extract content type and CID
    # URL patterns: /cache/{cid}, /recipes/{cid}, /effects/{cid}, /runs/{cid}
    from urllib.parse import urlparse

    parsed = urlparse(url)
    parts = [p for p in parsed.path.strip("/").split("/") if p]

    if len(parts) < 2:
        return JSONResponse({"error": "could not parse content URL"}, status_code=404)

    content_type = parts[0].rstrip("s")  # recipes -> recipe, runs -> run
    cid = parts[1]

    import database

    title = cid[:16]
    thumbnail_url = None

    # Look up metadata
    items = await database.get_item_types(cid)
    if items:
        meta = items[0]
        title = meta.get("filename") or meta.get("description") or title

        # Try friendly name
        actor_id = meta.get("actor_id")
        if actor_id:
            friendly = await database.get_friendly_name_by_cid(actor_id, cid)
            if friendly:
                title = friendly.get("display_name") or friendly.get("base_name", title)

        # Media items get a thumbnail
        if meta.get("type") == "media":
            artdag_url = os.getenv("APP_URL_ARTDAG", "https://celery-artdag.rose-ash.com")
            thumbnail_url = f"{artdag_url}/cache/{cid}/raw"

    elif content_type == "run":
        run = await database.get_run_cache(cid)
        if run:
            title = f"Run {cid[:12]}"

    artdag_url = os.getenv("APP_URL_ARTDAG", "https://celery-artdag.rose-ash.com")

    resp = {
        "version": "1.0",
        "type": "link",
        "title": title,
        "provider_name": "art-dag",
        "provider_url": artdag_url,
        "url": url,
    }
    if thumbnail_url:
        resp["thumbnail_url"] = thumbnail_url

    return JSONResponse(resp)
