from __future__ import annotations
import uuid
from django.http import HttpResponse, HttpResponseForbidden, HttpResponseNotFound
from django.shortcuts import render
from django.conf import settings
from django.utils.html import escape

from pxy_dashboard.utils.share import verify_token, DEFAULT_TTL
from pxy_sites.models import SiteRun

# --- Sites ---
def share_sites_card(request, search_id, token):
    # Django gives a UUID object when using <uuid:..>; normalize to str
    sid = str(search_id)
    try:
        uuid.UUID(sid)
    except Exception:
        return HttpResponseNotFound("Invalid search_id")
    try:
        payload = verify_token(token, max_age=DEFAULT_TTL)
        if payload.get("k") != "sites" or payload.get("sid") != sid:
            return HttpResponseForbidden("Bad token")
    except Exception:
        return HttpResponseForbidden("Expired or invalid token")

    # Load run by string id
    try:
        run = SiteRun.objects.get(search_id=sid)
    except SiteRun.DoesNotExist:
        return HttpResponseNotFound("Run not found")

    # ... rest unchanged ...



# --- SAMI ---
def share_sami_card(request, run_id, token):
    rid = str(run_id)  # normalize
    try:
        uuid.UUID(rid)
    except Exception:
        return HttpResponseNotFound("Invalid run_id")
    try:
        payload = verify_token(token, max_age=DEFAULT_TTL)
        if payload.get("k") != "sami" or payload.get("rid") != rid:
            return HttpResponseForbidden("Bad token")
    except Exception:
        return HttpResponseForbidden("Expired or invalid token")

    chart_url = f"{settings.MEDIA_URL}sami/sami_{rid}.png"
    ctx = {
        "title": f"SAMI · {payload.get('indicator', '')}",
        "indicator": payload.get("indicator"),
        "beta": payload.get("beta"),
        "r2": payload.get("r2"),
        "n": payload.get("n"),
        "chart_url": chart_url,
    }
    return render(request, "pxy_dashboard/share/sami_card.html", ctx)
