# retoor <retoor@molodetz.nl>

import logging
from typing import Annotated
from fastapi import Depends, APIRouter, Request
from devplacepy.models import AiModifierForm
from devplacepy.config import DEFAULT_MODIFIER_PROMPT
from devplacepy.database import get_table
from devplacepy.responses import action_result
from devplacepy.utils import clear_user_cache
from devplacepy.services.audit import record as audit

from devplacepy.routers.profile._shared import resolve_customization_target
from devplacepy.dependencies import json_or_form

logger = logging.getLogger(__name__)
router = APIRouter()

@router.post("/{username}/ai-modifier")
async def set_ai_modifier(
    request: Request,
    username: str,
    data: Annotated[AiModifierForm, Depends(json_or_form(AiModifierForm))],
):
    target, denied = resolve_customization_target(request, username)
    if denied is not None:
        return denied
    enabled = 1 if data.enabled else 0
    sync = 1 if data.sync else 0
    prompt = data.prompt.strip() or DEFAULT_MODIFIER_PROMPT
    get_table("users").update(
        {
            "uid": target["uid"],
            "ai_modifier_enabled": enabled,
            "ai_modifier_prompt": prompt,
            "ai_modifier_sync": sync,
        },
        ["uid"],
    )
    clear_user_cache(target["uid"])
    logger.info(
        f"AI modifier {'enabled' if enabled else 'disabled'} for {target['username']}"
    )
    audit.record(
        request,
        "profile.ai_modifier",
        target_type="user",
        target_uid=target["uid"],
        target_label=target["username"],
        new_value=enabled,
        summary=(
            f"{'enabled' if enabled else 'disabled'} AI modifier "
            f"for {target['username']}"
        ),
        links=[audit.target("user", target["uid"], target["username"])],
    )
    url = f"/profile/{target['username']}"
    return action_result(
        request,
        url,
        data={
            "url": url,
            "enabled": bool(enabled),
            "sync": bool(sync),
            "prompt": prompt,
        },
    )
