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

from agent.graph import reset_graph
from agent.prompt_utils import list_tool_prompts, read_tool_prompt, write_tool_prompt

router = APIRouter()


class ToolPromptUpdateRequest(BaseModel):
    content: str


@router.get("/api/agent/tool-prompts")
async def get_tool_prompts_list(request: Request):
    """List all available tool prompt files."""
    try:
        files = list_tool_prompts()
        return {"status": "success", "files": files}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/api/agent/tool-prompts/{filename}")
async def get_tool_prompt_content(filename: str, request: Request):
    """Get content of a specific tool prompt file."""
    try:
        content = read_tool_prompt(filename)
        if not content:
            # Try appending .txt if not present
            if not filename.endswith(".txt"):
                content = read_tool_prompt(filename + ".txt")

        return {"status": "success", "content": content}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/api/agent/tool-prompts/{filename}")
async def update_tool_prompt_content(filename: str, request: Request, body: ToolPromptUpdateRequest):
    """Update content of a tool prompt file and reset graph."""
    try:
        # Ensure filename is safe (basic check)
        if ".." in filename or "/" in filename or "\\" in filename:
            raise HTTPException(status_code=400, detail="Invalid filename")

        success = write_tool_prompt(filename, body.content)
        if not success:
            raise HTTPException(status_code=500, detail="Failed to write file")

        # Reset Graph to reload tools with new prompts
        reset_graph()

        return {"status": "success", "message": f"Tool prompt {filename} updated successfully. Graph reloaded."}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
