# app/api/admin_context.py

from fastapi import APIRouter, Depends
from pydantic import BaseModel
from app.core.auth import require_admin_key
import app.core.context as ctx
from app.db import database as db

router = APIRouter(prefix="/admin/context", tags=["Admin – Context"])


class ContextRead(BaseModel):
    allowed_topics:   list[str]
    blocked_phrases:  list[str]
    knowledge_base:   str
    system_prompt:    str


class ContextUpdate(BaseModel):
    allowed_topics:   list[str] | None = None
    blocked_phrases:  list[str] | None = None
    knowledge_base:   str | None       = None
    system_prompt:    str | None       = None


@router.get("", response_model=ContextRead)
async def get_context(_: bool = Depends(require_admin_key)):
    from app.db import database as db
    data = db.get_context()
    return ContextRead(**data)

@router.put("", response_model=ContextRead)
async def update_context(
    update: ContextUpdate,
    _: bool = Depends(require_admin_key),
):
    if update.allowed_topics  is not None: ctx.ALLOWED_TOPICS  = update.allowed_topics
    if update.blocked_phrases is not None: ctx.BLOCKED_PHRASES = update.blocked_phrases
    if update.knowledge_base  is not None: ctx.KNOWLEDGE_BASE  = update.knowledge_base
    if update.system_prompt   is not None: ctx.SYSTEM_PROMPT   = update.system_prompt

    from app.db import database as db
    db.update_context(
        allowed_topics  = ctx.ALLOWED_TOPICS,
        blocked_phrases = ctx.BLOCKED_PHRASES,
        knowledge_base  = ctx.KNOWLEDGE_BASE,
        system_prompt   = ctx.SYSTEM_PROMPT,
    )

    return ContextRead(
        allowed_topics  = ctx.ALLOWED_TOPICS,
        blocked_phrases = ctx.BLOCKED_PHRASES,
        knowledge_base  = ctx.KNOWLEDGE_BASE,
        system_prompt   = ctx.SYSTEM_PROMPT,
    )


@router.post("/reset", response_model=ContextRead)
async def reset_context(_: bool = Depends(require_admin_key)):
    from app.db import database as db
    from app.core import context as defaults
    db.update_context(
        allowed_topics  = defaults.ALLOWED_TOPICS,
        blocked_phrases = defaults.BLOCKED_PHRASES,
        knowledge_base  = defaults.KNOWLEDGE_BASE,
        system_prompt   = defaults.SYSTEM_PROMPT,
    )
    data = db.get_context()
    return ContextRead(**data)
