<?php

namespace XZD\AI\V5\Analytics;

use XZD\AI\V5\Core\Config;

/**
 * 成本预算预警 — 在 AI 调用后检查预算消耗并发送通知
 *
 * 三档预警: 50% / 80% / 95%，每档只触发一次（option 标记防重复）。
 * 通知方式: admin_email + Zibll 站内消息。
 */
class BudgetAlert
{
    private static ?BudgetAlert $instance = null;

    public static function instance(): self
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 每次 AI 调用后检查预算
     */
    public function checkAfterCall(float $costThisCall): void
    {
        // Config::get() 是实例方法，非静态调用
        $budget = (float) (Config::instance()->get('cost.monthly_budget', 0));
        if ($budget <= 0) return; // 未设置预算

        $spent = $this->getMonthSpent();
        $pct = round(($spent / $budget) * 100, 1);

        // 三档阈值
        $thresholds = [
            ['pct' => 50, 'key' => 'xzd_budget_alert_50_sent'],
            ['pct' => 80, 'key' => 'xzd_budget_alert_80_sent'],
            ['pct' => 95, 'key' => 'xzd_budget_alert_95_sent'],
        ];

        foreach ($thresholds as $t) {
            if ($pct >= $t['pct'] && !get_option($t['key'])) {
                $this->sendAlert($t['pct'], $spent, $budget, $pct);
                update_option($t['key'], current_time('mysql'), false);
            }
        }

        // 月度重置：新月份清除所有标记
        if ((int) wp_date('n') !== (int) get_option('xzd_budget_alert_month', 0)) {
            foreach ($thresholds as $t) {
                delete_option($t['key']);
            }
            update_option('xzd_budget_alert_month', (int) wp_date('n'), false);
        }
    }

    /**
     * 获取预警状态（供仪表盘展示）
     */
    public function getAlertStatus(): array
    {
        $budget = (float) Config::get('cost.monthly_budget', 0);
        if ($budget <= 0) return ['active' => false, 'pct' => 0, 'spent' => 0, 'budget' => 0];

        $spent = $this->getMonthSpent();
        $pct = round(($spent / $budget) * 100, 1);

        return [
            'active'    => true,
            'pct'       => $pct,
            'spent'     => round($spent, 2),
            'budget'    => $budget,
            'remaining' => round($budget - $spent, 2),
            'level'     => $pct >= 95 ? 'danger' : ($pct >= 80 ? 'warning' : ($pct >= 50 ? 'info' : 'normal')),
        ];
    }

    /**
     * 发送预警通知
     */
    private function sendAlert(int $level, float $spent, float $budget, float $pct): void
    {
        $siteName = get_bloginfo('name');
        $subject = "[{$siteName}] AI 费用预警 - 已使用 {$pct}%";
        $message = sprintf(
            "AI 综合插件月度预算预警\n\n" .
            "当前使用率: %.1f%%\n" .
            "已消耗: ¥%.2f\n" .
            "预算总额: ¥%.2f\n" .
            "剩余: ¥%.2f\n\n" .
            "请登录后台查看详情: %s",
            $pct, $spent, $budget, $budget - $spent,
            admin_url('admin.php?page=xzdbk-ai')
        );

        // 发送邮件通知管理员
        wp_mail(get_option('admin_email'), $subject, $message);

        // 通过适配器发送站内通知（三层降级：ZibMsg → zib_message表 → user_meta）
        $adminIds = get_users(['role' => 'administrator', 'fields' => 'ID']);
        if (!empty($adminIds)) {
            $adapter = \XZD\AI\V5\Theme\AdapterRegistry::getCurrent();
            $adapter->sendBulkNotification($adminIds, $subject, nl2br(esc_html($message)), 0);
        }
    }

    /**
     * 获取本月已消耗金额
     */
    private function getMonthSpent(): float
    {
        $tracker = CostTracker::instance();
        // getStats() 返回 total 汇总无 month 键，改用 getMonthSummary() 获取本月精确汇总
        $summary = $tracker->getMonthSummary();
        return (float) ($summary['month_cost'] ?? 0);
    }
}

// 引用外部类
use XZD\AI\V5\Core\Config;
use XZD\AI\V5\Analytics\CostTracker;
