# 宇之然内容创作平台 - 系统管理API

from datetime import datetime, date
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
import os

from ..database import get_db

router = APIRouter()

@router.get("/status")
async def get_system_status(db: Session = Depends(get_db)):
    """获取系统概览状态"""
    today = date.today()
    
    # 统计总数
    total_topics = db.query(func.count(Topic.id)).scalar()
    
    # 今日新选题数
    today_articles = db.query(func.count(Topic.id)).filter(
        func.date(Topic.created_at) == today
    ).scalar()
    
    # 各状态选题数量
    topics_by_status = {}
    for status in ["待处理", "待审查", "待发布", "已发布"]:
        count = db.query(func.count(Topic.id)).filter(
            Topic.status == status
        ).scalar()
        topics_by_status[status] = count
    
    return {
        "total_topics": total_topics,
        "today_articles": today_articles,
        "topics_by_status": topics_by_status,
        "generated_count": db.query(func.count(Topic.id)).filter(
            Topic.generated_at.isnot(None)
        ).scalar(),
        "published_count": db.query(func.count(Topic.id)).filter(
            Topic.published_at.isnot(None)
        ).scalar()
    }

@router.get("/pipeline/status")
async def get_pipeline_status():
    """获取流水线状态"""
    import subprocess
    import json
    
    # 检查各个模块的运行状态
    pipeline_modules = {
        "creator": {
            "exists": os.path.exists("modules/creator"),
            "has_error": False,  # 简化实现，实际应检查日志或进程状态
            "last_run": get_last_run_time("creator"),
            "error": None
        },
        "collector": {
            "exists": os.path.exists("modules/collector"),
            "has_error": False,
            "last_run": get_last_run_time("collector"),
            "error": None
        }
    }
    
    # 统计分布（这里应该从数据库查询，简化为静态数据）
    status_distribution = {
        "待处理": 0,
        "待审查": 0,
        "待发布": 0
    }
    
    # 实际实现中应该从数据库查询真实数据
    # for status in ["待处理", "待审查", "待发布"]:
    #     count = db.query(func.count(Topic.id)).filter(
    #         Topic.status == status
    #     ).scalar()
    #     status_distribution[status] = count
    
    return {
        "status_distribution": status_distribution,
        "pipeline_modules": pipeline_modules,
        "topics_count": 0  # 简化实现
    }

def get_last_run_time(module_name: str) -> str:
    """获取模块最后运行时间（简化实现）"""
    # 实际实现应检查日志文件或数据库记录
    return "2026-04-26 15:30:00"