import json, os
from django.utils import timezone
from apps.editor.models import Project

p = Project.objects.get(pk=8)
src = p.ai_suggestions.filter(is_active=True).order_by("-updated_at", "-created_at").first()
if src is None:
    print("ERROR: no active AISuggestion for project 8")
else:
    payload = src.structured_response or {}
    n_alts = len(payload.get("alternatives") or [])
    ts = timezone.now().strftime("%Y%m%d-%H%M%S")
    out_dir = "/home/altoquet/maxeditor/backend/backups"
    os.makedirs(out_dir, exist_ok=True)
    out_path = f"{out_dir}/aisuggestion_p8_id{src.id}_{ts}.json"
    with open(out_path, "w", encoding="utf-8") as f:
        json.dump({
            "project_id": 8,
            "src_id": src.id,
            "title": src.title,
            "prompt_name": src.prompt_name,
            "saved_at": timezone.now().isoformat(),
            "structured_response": payload,
            "raw_response": src.raw_response,
        }, f, ensure_ascii=False, indent=2)
    print(f"OK savestate -> {out_path} ({n_alts} alternativas, {os.path.getsize(out_path)} bytes)")
