#!/usr/bin/env python3
"""
大纲阶段：基于研究笔记生成文章大纲（数据库版）
"""

import json, datetime, logging, sys
from pathlib import Path
from typing import Dict

PROJECT_ROOT = Path(__file__).parent.parent
sys.path.insert(0, str(PROJECT_ROOT))

# 导入数据库辅助模块
from db_helper import get_topic_by_id

DATA_DIR = PROJECT_ROOT / "automation" / "data"
RESEARCH_DIR = DATA_DIR / "research"
OUTPUT_DIR = DATA_DIR / "outlines"
LOGS_DIR = PROJECT_ROOT / "automation" / "logs"
TODAY = datetime.datetime.now().strftime("%Y-%m-%d")

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s',
                    handlers=[logging.FileHandler(LOGS_DIR / f"outline_{TODAY}.log"), logging.StreamHandler()])
logger = logging.getLogger(__name__)

class Outliner:
    def __init__(self, topic_id: str):
        self.topic_id = topic_id
        self.topic = self._load_topic()
        research_file = RESEARCH_DIR / TODAY / f"{topic_id}_research.md"
        if not research_file.exists():
            raise FileNotFoundError(f"Research notes not found: {research_file}")
        self.research_notes = research_file.read_text(encoding='utf-8')
        self.output_dir = OUTPUT_DIR / TODAY
        self.output_dir.mkdir(parents=True, exist_ok=True)

    def _load_topic(self) -> Dict:
        topic = get_topic_by_id(self.topic_id)
        if not topic:
            raise ValueError(f"Topic {self.topic_id} not found")
        return topic

    def generate_outline(self) -> str:
        """生成文章大纲 Markdown（基于模板）"""
        title = self.topic['title']
        field = self.topic.get('field', '')
        core = self.topic.get('core_concept', '')
        pain = self.topic.get('audience_pain', '')
        angle = self.topic.get('unique_angle', '')

        # 解析研究笔记中的案例数量
        case_count = self.research_notes.count('### 案例')

        outline = f"""# 文章大纲：{title}

## 一、引言
- 开场场景/痛点引入
- 提出核心问题：{title}
- 点明文章价值

## 二、核心观点
{core}

## 三、受众痛点分析
{pain}

## 四、全球/行业趋势与案例
- 引用研究笔记中的 {case_count} 个案例，精选 2-3 个详述
- 数据支撑：提取研究笔记中的关键数据
- 趋势分析

## 五、本土落地建议
- 结合{field}领域特点
- 提供可执行的步骤
- 注意事项

## 六、独特视角：{angle}

## 七、行动指南（MVP）
1. 理解现状
2. 小范围试验
3. 评估效果
4. 形成习惯

## 八、总结与鼓励
- 回顾要点
- 呼吁行动

## 九、参考文献
- 从研究笔记中提取来源链接

---
*大纲生成时间：{TODAY}*
"""
        return outline

    def save(self):
        outline_text = self.generate_outline()
        out_path = self.output_dir / f"{self.topic_id}_outline.md"
        out_path.write_text(outline_text, encoding='utf-8')
        logger.info(f"大纲已保存: {out_path}")
        return out_path

def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--topic-id', required=True, help='选题ID')
    args = parser.parse_args()

    o = Outliner(args.topic_id)
    o.save()
    print(f"SUCCESS: Outline created for {args.topic_id}")
    sys.exit(0)

if __name__ == "__main__":
    main()
