import subprocess
from pathlib import Path
import logging
import os

logger = logging.getLogger(__name__)

# 计算项目根目录（从本文件位置上升4层）
PROJECT_ROOT = Path(__file__).resolve().parents[4]
# 允许环境变量覆盖（适合容器部署）
if os.getenv('PROJECT_ROOT'):
    PROJECT_ROOT = Path(os.getenv('PROJECT_ROOT'))

def run_creator(topic_id: str = None):
    """运行内容创作脚本，返回简略结果
    
    Args:
        topic_id: 可选，指定要创作的选题ID。不指定则创作优先级最高的选题。
    """
    script_path = PROJECT_ROOT / "scripts" / "creator.py"
    venv_python = PROJECT_ROOT / "platform" / "backend" / "venv" / "bin" / "python"
    if venv_python.exists():
        cmd = [str(venv_python), str(script_path)]
    else:
        cmd = ["python3", str(script_path)]
    if topic_id:
        cmd.extend(["--topic-id", topic_id])
    result = subprocess.run(
        cmd,
        cwd=str(PROJECT_ROOT),
        capture_output=True,
        text=True,
        timeout=1800  # 30分钟超时，避免AI撰写超时
    )
    if result.returncode != 0:
        logger.error(f"Creator failed: {result.stderr}")
        if topic_id:
            try:
                sync_topic_to_db(topic_id)
            except Exception as e:
                logger.warning(f"Sync after creation failed: {e}")
        return {"ok": False, "error": result.stderr}
    
    # 解析日志，找出选择了哪个选题
    topic_id = None
    for line in result.stdout.splitlines():
        if "选择了选题:" in line:
            # 格式: 2026-04-16 ... INFO - 选择了选题: 标题 (优先级: X)
            # 标题可能在行内，但ID不一定有。我们稍后用文件同步。
            logger.info(line.strip())
        if "选题" in line and "已标记为「待发布」" in line:
            # 如: 2026-04-16 ... INFO - 选题 A01 已标记为「待发布」
            import re
            from .sync import sync_topic_to_db
            m = re.search(r'选题\s+([A-Za-z0-9]+)', line)
            if m:
                topic_id = m.group(1)
    
    return {
        "ok": True,
        "topic_id": topic_id,
        "stdout": result.stdout[-1000:] if len(result.stdout) > 1000 else result.stdout
    }
