from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel
import os
import re
from agent.graph import reset_graph
from common.cache import bump_prompt_version

router = APIRouter()

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

# Allowed variables in prompt (single braces OK for these)
ALLOWED_VARIABLES = {"date_str"}

class PromptUpdateRequest(BaseModel):
    content: str

def validate_prompt_braces(content: str) -> tuple[bool, list[str]]:
    """
    Validate that all braces in prompt are properly escaped.
    Returns (is_valid, list of problematic patterns)
    """
    # Find all {word} patterns
    single_brace_pattern = re.findall(r'\{([^{}]+)\}', content)
    
    # Filter out allowed variables
    problematic = [
        var for var in single_brace_pattern 
        if var.strip() not in ALLOWED_VARIABLES and not var.startswith('{')
    ]
    
    return len(problematic) == 0, problematic

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"""
    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")
@rate_limit_service.limiter.limit("10/minute")
async def update_system_prompt_content(request: Request, body: PromptUpdateRequest):
    """Update system prompt content"""
    try:
        # Validate braces
        is_valid, problematic = validate_prompt_braces(body.content)
        
        if not is_valid:
            # Return warning but still allow save
            warning = (
                f"⚠️ Phát hiện {{...}} chưa escape: {problematic[:3]}... "
                f"Nếu đây là JSON, hãy dùng {{{{ }}}} thay vì {{ }}. "
                f"Prompt vẫn được lưu nhưng có thể gây lỗi khi chat."
            )
        else:
            warning = None
            
        # 1. Update file
        with open(PROMPT_FILE_PATH, "w", encoding="utf-8") as f:
            f.write(body.content)
            
        # 2. Bump prompt version in Redis (ALL workers will detect this)
        new_version = await bump_prompt_version()
        
        # 3. Reset local worker's Graph Singleton (immediate effect for this worker)
        reset_graph()
        
        response = {
            "status": "success", 
            "message": f"System prompt updated. Version: {new_version}. All workers will reload on next request.",
            "prompt_version": new_version
        }
        if warning:
            response["warning"] = warning
            
        return response
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


