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

from agent.prompt_utils import get_system_prompt_template, force_refresh_prompts, write_tool_prompt
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 local file)."""
    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):
    """Update system prompt (writes to local file)."""
    try:
        import os
        prompt_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "agent", "system_prompt.txt")
        prompt_path = os.path.normpath(prompt_path)

        with open(prompt_path, "w", encoding="utf-8") as f:
            f.write(body.content)

        # Force refresh caches
        force_refresh_prompts()
        reset_chain_cache()

        return {
            "status": "success",
            "message": "System prompt updated (local file). Caches refreshed.",
        }
    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."""
    try:
        force_refresh_prompts()
        reset_chain_cache()
        return {
            "status": "success",
            "message": "All prompt caches refreshed from local files.",
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
