import subprocess
from pathlib import Path
import logging
import os
import json
from datetime import datetime
from typing import List

logger = logging.getLogger(__name__)

# 计算项目根目录（从本文件位置上升4层）
PROJECT_ROOT = Path(__file__).resolve().parents[1]
if os.getenv('PROJECT_ROOT'):
    PROJECT_ROOT = Path(os.getenv('PROJECT_ROOT'))

def run_optimizer(topic_ids: List[str] = None):
    """运行合规优化脚本，返回报告摘要
    
    Args:
        topic_ids: 可选，指定要优化的选题ID列表。不指定则优化所有 draft 文章。
    """
    script_path = PROJECT_ROOT / "scripts" / "compliance_optimizer.py"
    cmd = ["python3", str(script_path)]
    if topic_ids:
        cmd.extend(["--topic-ids", ','.join(topic_ids)])
    logger.info(f"[DEBUG] Running optimizer with topic_ids={topic_ids}, cmd={' '.join(cmd)}")
    
    result = subprocess.run(
        cmd,
        cwd=str(PROJECT_ROOT),
        capture_output=True,
        text=True,
        timeout=600  # 10分钟
    )
    if result.returncode != 0:
        logger.error(f"Optimizer failed: {result.stderr}")
        return {"ok": False, "error": result.stderr}
    
    # 读取优化报告（优化脚本会在 today 的 drafts 目录生成报告）
    report_date = datetime.now().strftime("%Y-%m-%d")
    report_path = PROJECT_ROOT / "automation" / "data" / "drafts" / report_date / "optimization_report.json"
    if report_path.exists():
        report = json.loads(report_path.read_text(encoding='utf-8'))
        return {"ok": True, "report": report}
    else:
        logger.warning(f"Report not found: {report_path}")
        return {"ok": True, "report": None, "stdout": result.stdout}
