from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel

from agent.prompt_utils import get_system_prompt_template, force_refresh_prompts, LANGFUSE_SYSTEM_PROMPT_NAME, _get_langfuse
from agent.graph import reset_chain_cache

router = APIRouter()


class PromptUpdateRequest(BaseModel):
    content: str


from common.rate_limit import rate_limit_service


@router.get("/api/agent/system-prompt")
async def get_system_prompt_content(request: Request):
    """Get current system prompt content from Langfuse."""
    try:
        return {"status": "success", "content": get_system_prompt_template()}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/api/agent/system-prompt")
@rate_limit_service.limiter.limit("10/minute")
async def update_system_prompt_content(request: Request, body: PromptUpdateRequest):
    """Create new system prompt version in Langfuse."""
    try:
        lf = _get_langfuse()
        content = body.content
        if "{date_str}" in content and "{{date_str}}" not in content:
            content = content.replace("{date_str}", "{{date_str}}")

        prompt = lf.create_prompt(
            name=LANGFUSE_SYSTEM_PROMPT_NAME,
            prompt=content,
            labels=["production"],
            tags=["canifa", "system-prompt"],
            type="text",
        )
        return {
            "status": "success",
            "message": f"System prompt updated. Version: {prompt.version}",
            "prompt_version": prompt.version,
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/api/prompt/refresh")
async def refresh_prompt_cache(request: Request):
    """Force refresh all prompt caches immediately.
    Call this after updating prompts on Langfuse to take effect right away.
    """
    try:
        # 1) Force refresh Langfuse SDK cache (all prompts)
        force_refresh_prompts()
        # 2) Clear graph chain cache so it rebuilds with new prompt
        reset_chain_cache()
        return {
            "status": "success",
            "message": "All prompt caches refreshed. Next request will use the latest prompts.",
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
