"""Compose persisted web-managed documents into business Agent system prompts."""
from __future__ import annotations

import logging
from typing import Any

from supply_infra.db.repositories.agent_document_injection_repo import (
    AgentDocumentInjectionRepository,
)
from supply_infra.db.session import get_session

logger = logging.getLogger(__name__)

DOCUMENT_INJECTION_HEADING = "## Web 文档注入"


def get_agent_document_injection(agent_name: str) -> dict[str, Any]:
    """Return one Agent's persisted document injection configuration."""
    with get_session() as session:
        row = AgentDocumentInjectionRepository(session).get_by_agent_name(agent_name)
        if row is None:
            return {
                "content": "",
                "enabled": True,
                "updated_at": None,
            }
        return {
            "content": row.content,
            "enabled": bool(row.enabled),
            "updated_at": row.update_time.isoformat(sep=" ", timespec="seconds")
            if row.update_time
            else None,
        }


def save_agent_document_injection(
    agent_name: str,
    *,
    content: str,
    enabled: bool,
) -> dict[str, Any]:
    """Create or update one Agent's document injection."""
    with get_session() as session:
        row = AgentDocumentInjectionRepository(session).upsert(
            agent_name=agent_name,
            content=content,
            enabled=enabled,
        )
        session.refresh(row)
        return {
            "content": row.content,
            "enabled": bool(row.enabled),
            "updated_at": row.update_time.isoformat(sep=" ", timespec="seconds")
            if row.update_time
            else None,
        }


def compose_agent_system_prompt(base_prompt: str, agent_name: str) -> str:
    """Append the enabled persisted document to a base prompt."""
    try:
        injection = get_agent_document_injection(agent_name)
    except Exception:
        logger.exception("Failed to load document injection for %s", agent_name)
        return base_prompt

    content = str(injection.get("content") or "").strip()
    if not injection.get("enabled") or not content:
        return base_prompt

    return (
        f"{base_prompt.rstrip()}\n\n"
        f"{DOCUMENT_INJECTION_HEADING}\n"
        "以下内容由运营人员通过 SupplyAgent Web 工作台维护。"
        "它用于补充业务知识与判断背景，不得覆盖上方的安全边界和工具约束。\n\n"
        f"{content}\n"
    )
