#!/bin/bash
# 生产监控脚本

BASE_DIR="$(cd "$(dirname "$0")" && pwd)"
STATUS_FILE="$BASE_DIR/production_status.json"

echo "慢剧工作台 - 批量生产监控"
echo "=========================="

while true; do
    clear
    echo "$(date)"
    echo "批量生产监控面板"
    echo "=========================="
    
    if [ -f "$STATUS_FILE" ]; then
        # 使用Python解析JSON
        python3 -c "
import json
import os
from datetime import datetime

try:
    with open('$STATUS_FILE', 'r', encoding='utf-8') as f:
        status = json.load(f)
    
    print(f'批量ID: {status.get(\"batch_id\", \"N/A\")}')
    print(f'状态: {status.get(\"status\", \"unknown\")}')
    print(f'当前阶段: {status.get(\"current_phase\", \"unknown\")}')
    print(f'剧集进度: {status.get(\"completed_episodes\", 0)}/{status.get(\"total_episodes\", 0)}')
    print(f'进行中: {status.get(\"in_progress_episodes\", 0)}')
    print(f'失败: {status.get(\"failed_episodes\", 0)}')
    
    if 'start_time' in status:
        start = datetime.fromisoformat(status['start_time'].replace('Z', '+00:00'))
        now = datetime.now()
        elapsed = now - start
        print(f'运行时间: {int(elapsed.total_seconds()/60)}分钟')
    
    if 'last_updated' in status:
        last = datetime.fromisoformat(status['last_updated'].replace('Z', '+00:00'))
        now = datetime.now()
        since = now - last
        print(f'最后更新: {int(since.total_seconds())}秒前')
    
except Exception as e:
    print(f'读取状态失败: {e}')
"
    else
        echo "状态文件不存在"
    fi
    
    echo -e "\n操作:"
    echo "1. 刷新状态"
    echo "2. 查看日志"
    echo "3. 查看报告"
    echo "4. 退出监控"
    echo -e "\n选择: \c"
    
    read choice
    case $choice in
        1) continue ;;
        2) tail -20 "$BASE_DIR/logs/batch_manager.log" 2>/dev/null || echo "日志文件不存在"; read -p "按回车继续..." ;;
        3) ls -la "$BASE_DIR/reports/" 2>/dev/null || echo "报告目录不存在"; read -p "按回车继续..." ;;
        4) break ;;
        *) echo "无效选择"; sleep 1 ;;
    esac
done

echo "监控结束"
