from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
import os
from agent.graph import reset_graph

router = APIRouter()

PROMPT_FILE_PATH = os.path.join(os.path.dirname(__file__), "../agent/system_prompt.txt")

class PromptUpdateRequest(BaseModel):
    content: str

@router.get("/api/agent/system-prompt")
async def get_system_prompt_content():
    """Get current system prompt content"""
    # ... existing code ...
    try:
        if os.path.exists(PROMPT_FILE_PATH):
            with open(PROMPT_FILE_PATH, "r", encoding="utf-8") as f:
                content = f.read()
            return {"status": "success", "content": content}
        else:
            return {"status": "error", "message": "Prompt file not found"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/api/agent/system-prompt")
async def update_system_prompt_content(request: PromptUpdateRequest):
    """Update system prompt content"""
    try:
        # 1. Update file
        with open(PROMPT_FILE_PATH, "w", encoding="utf-8") as f:
            f.write(request.content)
            
        # 2. Reset Graph Singleton to force reload prompt
        reset_graph()
        
        return {"status": "success", "message": "System prompt updated successfully. Graph reloaded."}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
