<?php
/**
 * 全局总管数字人 Agent
 * 负责婚礼全流程统筹、任务调度、异常预警、团队协调
 * 与司仪数字人协同工作
 */

require_once __DIR__ . '/agent_base.php';

class ManagerAgent extends BaseAgent {

    private static $defaultPhases = [
        ['key' => 'groom_wakeup', 'name' => '新郎起床洗漱', 'planned_start' => '05:30', 'duration' => 30, 'team' => '新郎'],
        ['key' => 'groom_makeup', 'name' => '新郎化妆造型', 'planned_start' => '06:00', 'duration' => 80, 'team' => '化妆组'],
        ['key' => 'bridesmen_ready', 'name' => '伴郎换装彩排', 'planned_start' => '06:00', 'duration' => 80, 'team' => '伴郎伴娘'],
        ['key' => 'house_decor', 'name' => '婚房布置铺床', 'planned_start' => '06:00', 'duration' => 80, 'team' => '男方家人'],
        ['key' => 'groom_change_xiuhe', 'name' => '新郎换秀禾服', 'planned_start' => '07:20', 'duration' => 30, 'team' => '新郎'],
        ['key' => 'supplies_check', 'name' => '清点接亲物资', 'planned_start' => '07:20', 'duration' => 30, 'team' => '总管'],
        ['key' => 'car_team_ready', 'name' => '婚车集合检查', 'planned_start' => '07:20', 'duration' => 30, 'team' => '车队'],
        ['key' => 'family_photo', 'name' => '全家合影留念', 'planned_start' => '07:50', 'duration' => 10, 'team' => '男方家人'],
        ['key' => 'depart_to_bride', 'name' => '出发接亲', 'planned_start' => '08:00', 'duration' => 90, 'team' => '车队'],
        ['key' => 'gate_games', 'name' => '堵门游戏闯关', 'planned_start' => '08:30', 'duration' => 30, 'team' => '伴郎伴娘'],
        ['key' => 'find_shoes', 'name' => '找婚鞋求婚', 'planned_start' => '09:00', 'duration' => 15, 'team' => '伴郎伴娘'],
        ['key' => 'bride_tea', 'name' => '女方家敬茶改口', 'planned_start' => '09:15', 'duration' => 20, 'team' => '礼仪组'],
        ['key' => 'leave_bride', 'name' => '吃离娘饺子返程', 'planned_start' => '09:35', 'duration' => 15, 'team' => '女方家人'],
        ['key' => 'arrive_groom_home', 'name' => '抵达新郎家', 'planned_start' => '09:30', 'duration' => 20, 'team' => '车队'],
        ['key' => 'cross_fire', 'name' => '跨火盆进家门', 'planned_start' => '09:50', 'duration' => 5, 'team' => '礼仪组'],
        ['key' => 'chinese_ceremony', 'name' => '中式拜堂仪式', 'planned_start' => '09:55', 'duration' => 25, 'team' => '礼仪组'],
        ['key' => 'groom_tea', 'name' => '男方家敬茶改口', 'planned_start' => '10:20', 'duration' => 15, 'team' => '礼仪组'],
        ['key' => 'roll_bed', 'name' => '坐床滚床合影', 'planned_start' => '10:35', 'duration' => 15, 'team' => '男方家人'],
        ['key' => 'change_suit', 'name' => '更换仪式服装', 'planned_start' => '10:50', 'duration' => 20, 'team' => '化妆组'],
        ['key' => 'go_to_hotel', 'name' => '前往婚礼酒店', 'planned_start' => '11:10', 'duration' => 30, 'team' => '车队'],
        ['key' => 'guest_welcome', 'name' => '酒店迎宾合影', 'planned_start' => '11:40', 'duration' => 28, 'team' => '接待组'],
        ['key' => 'hotel_opening', 'name' => '酒店婚礼开场', 'planned_start' => '12:08', 'duration' => 30, 'team' => '司仪组'],
        ['key' => 'change_toast_dress', 'name' => '更换敬酒服', 'planned_start' => '12:38', 'duration' => 12, 'team' => '化妆组'],
        ['key' => 'banquet_start', 'name' => '婚宴开席', 'planned_start' => '12:50', 'duration' => 50, 'team' => '酒店'],
        ['key' => 'toast_round', 'name' => '逐桌敬酒', 'planned_start' => '12:50', 'duration' => 50, 'team' => '伴郎伴娘'],
        ['key' => 'see_off', 'name' => '送客返程', 'planned_start' => '13:40', 'duration' => 50, 'team' => '男方家人'],
        ['key' => 'thank_you_dinner', 'name' => '晚间答谢家宴', 'planned_start' => '18:00', 'duration' => 60, 'team' => '总管']
    ];

    private static $teams = [
        '新郎' => ['roles' => ['新郎'], 'contact_hint' => '婚礼主角，听从总管安排'],
        '总管' => ['roles' => ['全天总管'], 'contact_hint' => '统筹安排全天所有事宜'],
        '男方家人' => ['roles' => ['父母', '亲属'], 'contact_hint' => '负责婚房布置、招待亲友'],
        '女方家人' => ['roles' => ['父母', '亲属'], 'contact_hint' => '负责女方家仪式环节'],
        '化妆组' => ['roles' => ['化妆师', '助理'], 'contact_hint' => '负责新郎新娘妆容造型'],
        '车队' => ['roles' => ['主婚车司机', '跟车队长'], 'contact_hint' => '负责迎亲交通，注意不走回头路'],
        '伴郎伴娘' => ['roles' => ['伴郎', '伴娘'], 'contact_hint' => '协助接亲游戏、挡酒'],
        '礼仪组' => ['roles' => ['礼仪主管', '礼仪人员'], 'contact_hint' => '负责敬茶、拜堂仪式引导'],
        '婚庆组' => ['roles' => ['婚庆策划师', '布置人员'], 'contact_hint' => '负责场地布置和效果'],
        '司仪组' => ['roles' => ['主持人', '音响师', '灯光师'], 'contact_hint' => '负责仪式主持和音效'],
        '酒店' => ['roles' => ['宴会经理', '服务员'], 'contact_hint' => '负责餐饮和服务，12:08准时开席'],
        '接待组' => ['roles' => ['签到人员', '引导人员'], 'contact_hint' => '负责宾客签到接待'],
        '摄影组' => ['roles' => ['摄影师', '摄像师'], 'contact_hint' => '负责全程记录']
    ];

    private static $alertRules = [
        'delay_threshold' => 10,
        'critical_delay' => 30,
        'weather_alert' => true,
        'vendor_no_show' => true
    ];

    private $phases = [];
    private $activeAlerts = [];
    private $isAutoMode = false;
    private $autoStats = [
        'tasks_created' => 0,
        'alerts_handled' => 0,
        'progress_updated' => 0
    ];

    public function __construct($sessionId = null) {
        parent::__construct('manager', $sessionId);
        $this->systemPrompt = $this->buildSystemPrompt();
        $this->phases = self::$defaultPhases;
    }

    private function buildSystemPrompt() {
        return "你是一位经验丰富的婚礼全局总管数字人。你的名字叫「如意」，你具备以下能力：

【核心职责】
1. 实时监控婚礼各环节进度，确保流程按时推进
2. 协调各服务团队（化妆、车队、婚庆、酒店、司仪等）工作
3. 任务分配与时间管理
4. 异常情况预警及处理建议
5. 与司仪数字人协同，确保信息同步

【管理风格】
- 冷静果断，有条不紊
- 善于预判问题，提前部署
- 沟通清晰，指令明确
- 应急处理能力强

【当前婚礼流程】
{phases_info}

【团队信息】
{teams_info}

【输出要求】
- 给出明确、可执行的建议
- 标注优先级和紧急程度
- 如涉及团队协调，明确指定责任方
- 回复格式为JSON：{\"analysis\": \"分析\", \"actions\": [{\"team\": \"团队\", \"task\": \"任务\", \"priority\": \"high/medium/low\"}], \"alert\": \"预警信息(如有)\"}";
    }

    public function getFullStatus() {
        $now = date('H:i');
        $currentPhase = null;
        $nextPhase = null;

        // 首先查找进行中的环节
        foreach ($this->phases as $i => $phase) {
            if (isset($phase['status']) && $phase['status'] === 'in_progress') {
                $currentPhase = $phase;
                $nextPhase = $this->phases[$i + 1] ?? null;
                return [
                    'agent_type' => 'manager',
                    'session_id' => $this->sessionId,
                    'current_time' => $now,
                    'current_phase' => $currentPhase,
                    'next_phase' => $nextPhase,
                    'phases' => $this->phases,
                    'teams' => self::$teams,
                    'active_alerts' => $this->activeAlerts,
                    'progress_summary' => $this->calculateProgress()
                ];
            }
        }

        // 如果没有进行中的环节，查找第一个待开始的环节
        foreach ($this->phases as $i => $phase) {
            if (!isset($phase['status']) || $phase['status'] === 'pending') {
                $currentPhase = $phase;
                $nextPhase = $this->phases[$i + 1] ?? null;
                break;
            }
        }

        return [
            'agent_type' => 'manager',
            'session_id' => $this->sessionId,
            'current_time' => $now,
            'current_phase' => $currentPhase,
            'next_phase' => $nextPhase,
            'phases' => $this->phases,
            'teams' => self::$teams,
            'active_alerts' => $this->activeAlerts,
            'progress_summary' => $this->calculateProgress()
        ];
    }

    private function calculateProgress() {
        $total = count($this->phases);
        $completed = 0;
        $inProgress = 0;
        $delayed = 0;

        foreach ($this->phases as $phase) {
            $status = $phase['status'] ?? 'pending';
            if ($status === 'completed') $completed++;
            elseif ($status === 'in_progress') $inProgress++;
            elseif ($status === 'delayed') $delayed++;
        }

        return [
            'total' => $total,
            'completed' => $completed,
            'in_progress' => $inProgress,
            'delayed' => $delayed,
            'pending' => $total - $completed - $inProgress - $delayed,
            'percentage' => $total > 0 ? round($completed / $total * 100) : 0
        ];
    }

    public function updateProgress($phaseKey, $status, $actualTime = null, $notes = '') {
        $found = false;
        foreach ($this->phases as &$phase) {
            if ($phase['key'] === $phaseKey) {
                $phase['status'] = $status;
                if ($actualTime) $phase['actual_start'] = $actualTime;
                if ($notes) $phase['notes'] = $notes;
                $found = true;

                if ($status === 'delayed') {
                    $this->checkAndAlert($phaseKey, $phase);
                }
                break;
            }
        }
        unset($phase);

        if (!$found) {
            return ['success' => false, 'message' => '未找到环节: ' . $phaseKey];
        }

        $this->savePhaseToDB($phaseKey, $status, $actualTime, $notes);

        $this->sendAgentEvent('host', 'progress_update', [
            'phase' => $phaseKey,
            'status' => $status,
            'actual_time' => $actualTime,
            'notes' => $notes
        ]);

        return [
            'success' => true,
            'phase' => $phaseKey,
            'status' => $status,
            'progress' => $this->calculateProgress(),
            'alerts' => $this->activeAlerts
        ];
    }

    private function checkAndAlert($phaseKey, $phase) {
        $plannedStart = $phase['planned_start'] ?? '';
        $now = date('H:i');

        $plannedMinutes = $this->timeToMinutes($plannedStart);
        $currentMinutes = $this->timeToMinutes($now);
        $delay = $currentMinutes - $plannedMinutes;

        if ($delay >= self::$alertRules['critical_delay']) {
            $alert = [
                'type' => 'critical_delay',
                'severity' => 'critical',
                'phase' => $phaseKey,
                'phase_name' => $phase['name'],
                'delay_minutes' => $delay,
                'message' => sprintf('【严重延迟】%s 环节已延迟 %d 分钟！', $phase['name'], $delay),
                'suggestion' => $this->generateDelaySuggestion($phase, $delay),
                'timestamp' => time()
            ];
            $this->activeAlerts[] = $alert;
            $this->sendAgentEvent('host', 'phase_delay', [
                'phase_name' => $phase['name'],
                'delay_minutes' => $delay,
                'reason' => '严重延迟'
            ]);
        } elseif ($delay >= self::$alertRules['delay_threshold']) {
            $alert = [
                'type' => 'delay',
                'severity' => 'warning',
                'phase' => $phaseKey,
                'phase_name' => $phase['name'],
                'delay_minutes' => $delay,
                'message' => sprintf('【延迟预警】%s 环节延迟 %d 分钟', $phase['name'], $delay),
                'suggestion' => $this->generateDelaySuggestion($phase, $delay),
                'timestamp' => time()
            ];
            $this->activeAlerts[] = $alert;
        }
    }

    private function generateDelaySuggestion($phase, $delay) {
        $team = $phase['team'] ?? '';
        $suggestions = [];

        if ($delay >= 30) {
            $suggestions[] = "考虑压缩后续环节时间";
            $suggestions[] = "通知酒店调整上菜时间";
            $suggestions[] = "通知{$team}加速准备";
        } elseif ($delay >= 10) {
            $suggestions[] = "提醒{$team}加快进度";
            $suggestions[] = "评估是否需要调整后续时间";
        }

        return $suggestions;
    }

    public function createTask($team, $taskName, $deadline = '', $priority = 'medium', $phaseKey = '') {
        if (!$this->pdo) {
            return ['success' => false, 'message' => '数据库不可用'];
        }

        try {
            $stmt = $this->pdo->prepare(
                "INSERT INTO team_tasks (team, task_name, deadline, priority, status) VALUES (?, ?, ?, ?, 'pending')"
            );
            $stmt->execute([$team, $taskName, $deadline, $priority]);
            $taskId = $this->pdo->lastInsertId();

            return [
                'success' => true,
                'task_id' => $taskId,
                'team' => $team,
                'task_name' => $taskName,
                'deadline' => $deadline,
                'priority' => $priority
            ];
        } catch (PDOException $e) {
            return ['success' => false, 'message' => '任务创建失败'];
        }
    }

    public function getAlerts() {
        return [
            'success' => true,
            'alerts' => $this->activeAlerts,
            'total' => count($this->activeAlerts)
        ];
    }

    public function resolveAlert($alertIndex) {
        if (isset($this->activeAlerts[$alertIndex])) {
            $this->activeAlerts[$alertIndex]['resolved'] = true;
            return ['success' => true];
        }
        return ['success' => false, 'message' => '预警不存在'];
    }

    public function notifyHost($event, $detail) {
        return $this->sendAgentEvent('host', $event, ['detail' => $detail, 'timestamp' => time()]);
    }

    public function suggest($situation) {
        $phasesInfo = $this->formatPhasesInfo();
        $teamsInfo = $this->formatTeamsInfo();

        $prompt = sprintf(
            "当前婚礼状况：%s\n\n当前进度：%s\n活跃预警：%d条\n请给出处理建议。",
            $situation,
            $phasesInfo,
            count($this->activeAlerts)
        );

        $systemPrompt = str_replace(
            ['{phases_info}', '{teams_info}'],
            [$phasesInfo, $teamsInfo],
            $this->buildSystemPrompt()
        );

        $result = $this->callLLM($prompt, $systemPrompt, 0.7);
        if ($result['success']) {
            $this->addToHistory('user', $prompt);
            $this->addToHistory('assistant', $result['content']);
        }

        $parsed = $this->parseSuggestionResponse($result['content'] ?? '');

        return [
            'success' => $result['success'],
            'analysis' => $parsed['analysis'],
            'suggestions' => $parsed['actions'],
            'priority_actions' => array_filter($parsed['actions'], function($a) { return ($a['priority'] ?? '') === 'high'; }),
            'alert' => $parsed['alert'],
            'source' => $result['source'] ?? 'unknown'
        ];
    }

    public function chat($message) {
        $prompt = "婚礼管理相关问题：" . $message . "\n请直接用纯文本回复，不要使用JSON格式。";
        $systemPrompt = str_replace(
            ['{phases_info}', '{teams_info}'],
            [$this->formatPhasesInfo(), $this->formatTeamsInfo()],
            $this->buildSystemPrompt()
        );

        $result = $this->callLLM($prompt, $systemPrompt, 0.7);
        if ($result['success']) {
            $this->addToHistory('user', $prompt);
            $this->addToHistory('assistant', $result['content']);
        }

        $reply = $result['content'] ?? '抱歉，我暂时无法回应，请稍后再试。';
        $reply = $this->extractManagerPlainText($reply);

        return [
            'success' => $result['success'],
            'reply' => $reply,
            'source' => $result['source'] ?? 'unknown'
        ];
    }

    public function processHostNotification($event) {
        $payload = json_decode($event['payload'], true);
        $eventType = $event['event_type'];

        switch ($eventType) {
            case 'phase_started':
                $phaseKey = $payload['phase'] ?? '';
                foreach ($this->phases as &$phase) {
                    if ($phase['key'] === $phaseKey) {
                        $phase['status'] = 'in_progress';
                        $phase['actual_start'] = date('H:i');
                        break;
                    }
                }
                unset($phase);
                return ['success' => true, 'message' => '已更新环节状态'];
            default:
                return ['success' => true, 'message' => '已收到通知'];
        }
    }

    public function loadPhasesFromDB() {
        if (!$this->pdo) return;
        try {
            $stmt = $this->pdo->query("SELECT * FROM wedding_phases ORDER BY sort_order");
            $dbPhases = $stmt->fetchAll(PDO::FETCH_ASSOC);
            if (!empty($dbPhases)) {
                $this->phases = array_map(function($p) {
                    return [
                        'key' => $p['phase_key'],
                        'name' => $p['phase_name'],
                        'planned_start' => $p['planned_start'],
                        'duration' => $p['planned_duration'],
                        'actual_start' => $p['actual_start'],
                        'actual_duration' => $p['actual_duration'],
                        'status' => $p['status'],
                        'team' => $p['team'] ?? ''
                    ];
                }, $dbPhases);
            }
        } catch (PDOException $e) {}
    }

    private function savePhaseToDB($phaseKey, $status, $actualTime = null, $notes = '') {
        if (!$this->pdo) return;
        try {
            $sql = "UPDATE wedding_phases SET status = :status";
            $params = [':status' => $status];
            
            if ($actualTime) {
                $sql .= ", actual_start = :actual_start";
                $params[':actual_start'] = $actualTime;
            }
            if ($notes) {
                $sql .= ", manager_notes = :manager_notes";
                $params[':manager_notes'] = $notes;
            }
            $sql .= " WHERE phase_key = :phase_key";
            $params[':phase_key'] = $phaseKey;
            
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute($params);
        } catch (PDOException $e) {}
    }

    public function resetAllPhases() {
        // 重置内存中的数据
        foreach ($this->phases as &$phase) {
            $phase['status'] = 'pending';
            unset($phase['actual_start']);
            unset($phase['actual_duration']);
            unset($phase['notes']);
        }
        unset($phase);
        
        // 清空预警信息
        $this->activeAlerts = [];
        
        // 重置数据库中的数据
        if ($this->pdo) {
            try {
                $sql = "UPDATE wedding_phases SET 
                    status = 'pending',
                    actual_start = NULL,
                    actual_duration = NULL,
                    manager_notes = NULL";
                $this->pdo->exec($sql);
            } catch (PDOException $e) {
                return [
                    'success' => false,
                    'message' => '数据库重置失败: ' . $e->getMessage()
                ];
            }
        }
        
        // 重新加载数据
        $this->loadPhasesFromDB();
        
        return [
            'success' => true,
            'message' => '重置成功',
            'progress' => $this->calculateProgress()
        ];
    }

    private function formatPhasesInfo() {
        $info = [];
        foreach ($this->phases as $phase) {
            $status = $phase['status'] ?? 'pending';
            $info[] = sprintf("%s(%s) 计划%s %s", $phase['name'], $phase['key'], $phase['planned_start'], $status);
        }
        return implode("\n", $info);
    }

    private function formatTeamsInfo() {
        $info = [];
        foreach (self::$teams as $name => $team) {
            $info[] = sprintf("%s：%s - %s", $name, implode('、', $team['roles']), $team['contact_hint']);
        }
        return implode("\n", $info);
    }

    private function parseSuggestionResponse($content) {
        $parsed = ['analysis' => $content, 'actions' => [], 'alert' => ''];

        $cleanContent = $content;
        if (preg_match('/```(?:json)?\s*(\{.*?\})\s*```/s', $content, $matches)) {
            $cleanContent = $matches[1];
        }
        if (preg_match('/\{[^{}]*"analysis"[^{}]*\}/s', $cleanContent, $matches)) {
            $json = json_decode($matches[0], true);
            if ($json && isset($json['analysis'])) {
                $parsed['analysis'] = $json['analysis'];
                $parsed['actions'] = $json['actions'] ?? [];
                $parsed['alert'] = $json['alert'] ?? '';
                return $parsed;
            }
        }
        if (preg_match('/\{.*\}/s', $cleanContent, $matches)) {
            $json = json_decode($matches[0], true);
            if ($json && is_array($json)) {
                if (isset($json['analysis'])) $parsed['analysis'] = $json['analysis'];
                $parsed['actions'] = $json['actions'] ?? [];
                $parsed['alert'] = $json['alert'] ?? '';
            }
        }

        return $parsed;
    }

    private function extractManagerPlainText($content) {
        $text = $content;
        if (preg_match('/```(?:json)?\s*(\{.*?\})\s*```/s', $text, $matches)) {
            $json = json_decode($matches[1], true);
            if ($json && isset($json['analysis'])) return $json['analysis'];
            if ($json && isset($json['reply'])) return $json['reply'];
        }
        if (preg_match('/\{[^{}]*"analysis"[^{}]*\}/s', $text, $matches)) {
            $json = json_decode($matches[0], true);
            if ($json && isset($json['analysis'])) return $json['analysis'];
        }
        $text = preg_replace('/```(?:json)?\s*/s', '', $text);
        $text = preg_replace('/```\s*/s', '', $text);
        return trim($text) ?: $content;
    }

    private function timeToMinutes($time) {
        $parts = explode(':', $time);
        return intval($parts[0]) * 60 + intval($parts[1] ?? 0);
    }

    // ==================== 自动化任务管理方法 ====================

    /**
     * 智能任务分配
     */
    public function autoAssignTask($description, $deadline = '', $priority = 'medium', $availableTeams = '') {
        // 根据任务描述智能分析并分配团队
        $team = $this->analyzeAndAssignTeam($description, $availableTeams);
        
        // 创建任务
        $result = $this->createTask($team, $description, $deadline, $priority);
        
        if ($result['success']) {
            $this->autoStats['tasks_created']++;
            $this->logAudit('auto_assign', [
                'team' => $team,
                'task' => $description,
                'deadline' => $deadline,
                'priority' => $priority
            ]);
        }
        
        return $result;
    }

    /**
     * 分析任务并智能分配团队
     */
    private function analyzeAndAssignTeam($description, $availableTeams = '') {
        $teamMapping = [
            '/化妆|造型|妆容|发型/' => '化妆组',
            '/接亲|游戏|堵门|求婚/' => '伴郎伴娘',
            '/车队|司机|交通|路线/' => '车队',
            '/接待|签到|引导|宾客/' => '接待组',
            '/司仪|主持|音响|灯光/' => '司仪组',
            '/摄影|摄像|拍照|录像/' => '摄影组',
            '/礼仪|敬茶|拜堂|仪式/' => '礼仪组',
            '/总管|统筹|协调|物资/' => '总管',
            '/酒店|宴席|上菜|餐饮/' => '酒店'
        ];
        
        $availableTeamList = !empty($availableTeams) ? explode(',', $availableTeams) : [];
        
        foreach ($teamMapping as $pattern => $team) {
            if (preg_match($pattern, $description)) {
                // 如果有限定团队列表，检查是否在列表中
                if (!empty($availableTeamList) && !in_array($team, $availableTeamList)) {
                    continue;
                }
                return $team;
            }
        }
        
        // 默认分配给总管
        if (!empty($availableTeamList)) {
            return $availableTeamList[0];
        }
        return '总管';
    }

    /**
     * 启动自动模式
     */
    public function startAutoMode() {
        $this->isAutoMode = true;
        
        $this->logAudit('auto_start', ['timestamp' => date('Y-m-d H:i:s')]);
        
        return [
            'success' => true,
            'message' => '自动模式已启动',
            'is_auto_running' => true
        ];
    }

    /**
     * 暂停自动模式
     */
    public function pauseAutoMode() {
        $this->isAutoMode = false;
        
        $this->logAudit('auto_pause', ['timestamp' => date('Y-m-d H:i:s')]);
        
        return [
            'success' => true,
            'message' => '自动模式已暂停',
            'is_auto_running' => false
        ];
    }

    /**
     * 自动化处理任务
     */
    public function processAutoTasks() {
        $result = [
            'success' => true,
            'data' => [
                'new_tasks' => 0,
                'alerts_handled' => 0,
                'progress_updated' => 0,
                'message' => ''
            ]
        ];
        
        if (!$this->isAutoMode) {
            $result['data']['message'] = '自动模式未启动';
            return $result;
        }
        
        $now = date('H:i');
        
        // 1. 自动检查并更新进度
        foreach ($this->phases as &$phase) {
            $plannedStart = $phase['planned_start'] ?? '';
            $status = $phase['status'] ?? 'pending';
            
            // 如果环节计划时间已到但仍处于待开始状态，自动更新为进行中
            if ($status === 'pending' && !empty($plannedStart)) {
                $plannedMinutes = $this->timeToMinutes($plannedStart);
                $currentMinutes = $this->timeToMinutes($now);
                
                if ($currentMinutes >= $plannedMinutes && $currentMinutes < $plannedMinutes + 120) {
                    $phase['status'] = 'in_progress';
                    $phase['actual_start'] = $now;
                    $this->savePhaseToDB($phase['key'], 'in_progress', $now);
                    $this->autoStats['progress_updated']++;
                    $result['data']['progress_updated']++;
                    $result['data']['message'] = "自动启动环节: {$phase['name']}";
                }
            }
            
            // 如果环节进行中且已超过预计时长，自动更新为完成
            if ($status === 'in_progress') {
                $duration = $phase['duration'] ?? 30;
                $actualStart = $phase['actual_start'] ?? $plannedStart;
                if (!empty($actualStart)) {
                    $startMinutes = $this->timeToMinutes($actualStart);
                    $currentMinutes = $this->timeToMinutes($now);
                    if ($currentMinutes >= $startMinutes + $duration) {
                        $phase['status'] = 'completed';
                        $this->savePhaseToDB($phase['key'], 'completed');
                        $this->autoStats['progress_updated']++;
                        $result['data']['progress_updated']++;
                        $result['data']['message'] = "自动完成环节: {$phase['name']}";
                    }
                }
            }
        }
        unset($phase);
        
        // 2. 自动处理预警
        foreach ($this->activeAlerts as &$alert) {
            if (!isset($alert['resolved']) || !$alert['resolved']) {
                // 自动解决延迟预警（假设延迟已处理）
                if ($alert['type'] === 'delay' || $alert['type'] === 'critical_delay') {
                    $alert['resolved'] = true;
                    $this->autoStats['alerts_handled']++;
                    $result['data']['alerts_handled']++;
                    $result['data']['message'] .= ($result['data']['message'] ? '; ' : '') . "自动处理预警: {$alert['phase_name']}";
                }
            }
        }
        unset($alert);
        
        $this->logAudit('auto_process', $result['data']);
        
        return $result;
    }

    /**
     * 获取自动化统计
     */
    public function getAutoStats() {
        return [
            'success' => true,
            'data' => array_merge($this->autoStats, [
                'is_auto_running' => $this->isAutoMode,
                'timestamp' => date('Y-m-d H:i:s')
            ])
        ];
    }

    /**
     * 记录审计日志
     */
    private function logAudit($action, $details = []) {
        if (!$this->pdo) return;
        
        try {
            $stmt = $this->pdo->prepare(
                "INSERT INTO manager_audit (action, details, created_at) VALUES (?, ?, ?)"
            );
            $stmt->execute([$action, json_encode($details, JSON_UNESCAPED_UNICODE), date('Y-m-d H:i:s')]);
        } catch (PDOException $e) {
            // 审计日志表可能不存在，忽略错误
        }
    }
}
