"""AI 运行日志服务 — biz.ai_run_logs 表的 CRUD 操作。

每次 Application API 调用前创建 pending 记录，调用过程中更新状态，
调用结束后记录结果。同时提供日/月 token 聚合查询，实现 UsageProvider 协议
以便注入 BudgetTracker。

request_prompt 写入前截断为前 2000 字符，避免大 prompt 占用过多存储。
"""

from __future__ import annotations

from datetime import datetime, timezone
from typing import Callable

import psycopg2.extensions

from app.services.runtime_context import LIVE_INSTANCE_ID, MODE_LIVE, MODE_SANDBOX, get_runtime_context

# prompt 最大存储长度
# 2026-04-22：2000→8000。app2_finance 真实 prompt 约 4-8KB（72 组合财务看板 + 中文 key 膨胀），
# 2000 字符截断会丢掉 optimization-critical 字段（如 discount_items 含团购折扣明细），
# admin-web 调用详情页无法完整审阅 → 提高到 8000 覆盖绝大部分场景
_MAX_PROMPT_LENGTH = 8000


def _truncate_prompt(prompt: str | None) -> str | None:
    """截断 prompt 为 _MAX_PROMPT_LENGTH 字符上限。None 原样返回。"""
    if prompt is None:
        return None
    return prompt[:_MAX_PROMPT_LENGTH]


class AIRunLogService:
    """AI 运行日志 CRUD，实现 UsageProvider 协议。

    构造函数接受 get_conn callable，每次操作时获取数据库连接，
    避免长期持有连接导致超时或连接池耗尽。
    """

    def __init__(self, get_conn: Callable[[], psycopg2.extensions.connection]) -> None:
        self._get_conn = get_conn

    # ── 创建 ──────────────────────────────────────────────

    def create_log(
        self,
        site_id: int,
        app_type: str,
        trigger_type: str,
        *,
        member_id: int | None = None,
        request_prompt: str | None = None,
        session_id: str | None = None,
    ) -> int:
        """创建日志记录（status: pending），返回 log_id。

        request_prompt 自动截断为前 2000 字符。
        """
        truncated = _truncate_prompt(request_prompt)
        conn = self._get_conn()
        try:
            ctx = get_runtime_context(site_id, conn=conn)
            runtime_mode = MODE_SANDBOX if ctx.is_sandbox else MODE_LIVE
            sandbox_instance_id = ctx.sandbox_instance_id if ctx.is_sandbox else LIVE_INSTANCE_ID
            with conn.cursor() as cur:
                cur.execute(
                    """
                    INSERT INTO biz.ai_run_logs
                        (site_id, app_type, trigger_type, member_id,
                         request_prompt, session_id, status,
                         runtime_mode, sandbox_instance_id)
                    VALUES (%s, %s, %s, %s, %s, %s, 'pending', %s, %s)
                    RETURNING id
                    """,
                    (site_id, app_type, trigger_type, member_id,
                     truncated, session_id, runtime_mode, sandbox_instance_id),
                )
                row = cur.fetchone()
                assert row is not None, "INSERT RETURNING 应返回 id"
                log_id: int = row[0]
            conn.commit()
            return log_id
        except Exception:
            conn.rollback()
            raise

    # ── 状态转换 ──────────────────────────────────────────

    def update_running(self, log_id: int) -> None:
        """更新为 running。"""
        conn = self._get_conn()
        try:
            with conn.cursor() as cur:
                cur.execute(
                    """
                    UPDATE biz.ai_run_logs
                       SET status = 'running'
                     WHERE id = %s
                    """,
                    (log_id,),
                )
            conn.commit()
        except Exception:
            conn.rollback()
            raise

    def update_success(
        self,
        log_id: int,
        response_text: str,
        tokens_used: int,
        latency_ms: int,
    ) -> None:
        """更新为 success，记录响应、token 消耗和耗时。"""
        now = datetime.now(timezone.utc)
        conn = self._get_conn()
        try:
            with conn.cursor() as cur:
                cur.execute(
                    """
                    UPDATE biz.ai_run_logs
                       SET status        = 'success',
                           response_text  = %s,
                           tokens_used    = %s,
                           latency_ms     = %s,
                           finished_at    = %s
                     WHERE id = %s
                    """,
                    (response_text, tokens_used, latency_ms, now, log_id),
                )
            conn.commit()
        except Exception:
            conn.rollback()
            raise

    def update_failed(
        self,
        log_id: int,
        error_message: str,
        latency_ms: int,
    ) -> None:
        """更新为 failed，记录错误信息和耗时。"""
        now = datetime.now(timezone.utc)
        conn = self._get_conn()
        try:
            with conn.cursor() as cur:
                cur.execute(
                    """
                    UPDATE biz.ai_run_logs
                       SET status        = 'failed',
                           error_message  = %s,
                           latency_ms     = %s,
                           finished_at    = %s
                     WHERE id = %s
                    """,
                    (error_message, latency_ms, now, log_id),
                )
            conn.commit()
        except Exception:
            conn.rollback()
            raise

    def update_timeout(self, log_id: int, latency_ms: int) -> None:
        """更新为 timeout。"""
        now = datetime.now(timezone.utc)
        conn = self._get_conn()
        try:
            with conn.cursor() as cur:
                cur.execute(
                    """
                    UPDATE biz.ai_run_logs
                       SET status      = 'timeout',
                           latency_ms  = %s,
                           finished_at = %s
                     WHERE id = %s
                    """,
                    (latency_ms, now, log_id),
                )
            conn.commit()
        except Exception:
            conn.rollback()
            raise

    # ── UsageProvider 协议实现 ────────────────────────────

    def get_daily_usage(self) -> int:
        """聚合今日 token 消耗（status='success'，created_at 为今日）。"""
        conn = self._get_conn()
        with conn.cursor() as cur:
            cur.execute(
                """
                SELECT COALESCE(SUM(tokens_used), 0)
                  FROM biz.ai_run_logs
                 WHERE status = 'success'
                   AND created_at >= CURRENT_DATE
                   AND created_at <  CURRENT_DATE + INTERVAL '1 day'
                """
            )
            row = cur.fetchone()
            return int(row[0]) if row else 0

    def get_monthly_usage(self) -> int:
        """聚合本月 token 消耗（status='success'，created_at 为本月）。"""
        conn = self._get_conn()
        with conn.cursor() as cur:
            cur.execute(
                """
                SELECT COALESCE(SUM(tokens_used), 0)
                  FROM biz.ai_run_logs
                 WHERE status = 'success'
                   AND created_at >= date_trunc('month', CURRENT_DATE)
                   AND created_at <  date_trunc('month', CURRENT_DATE) + INTERVAL '1 month'
                """
            )
            row = cur.fetchone()
            return int(row[0]) if row else 0
