#!/usr/bin/env python3
"""post_mortem.py - 知微历史报告复盘 + 自我改进引擎

读取所有历史报告,提炼分析模式,生成升级方案。
"""

import json
import re
from collections import defaultdict
from datetime import datetime
from pathlib import Path

DATA_DIR = Path(__file__).parent / "data"
REPORTS_DIR = DATA_DIR / "reports"


def load_reports():
    reports = []
    for f in sorted(REPORTS_DIR.iterdir()):
        if f.suffix == ".json" and f.stat().st_size > 200:
            try:
                reports.append(json.loads(f.read_text()))
            except:
                pass
    return reports


def analyze_stock_timeline(code):
    """提取某只股票在所有报告中的分析时间线"""
    entries = []
    for r in load_reports():
        content = r.get("content", "")
        if code in content:
            lines = content.split("\n")
            for i, line in enumerate(lines):
                if code in line and ("止损" in line or "止盈" in line or "补仓" in line or "买入" in line or "卖出" in line or "持有" in line or "减仓" in line):
                    entries.append({
                        "time": r.get("created_at", ""),
                        "type": r.get("type", ""),
                        "title": r.get("title", ""),
                        "line": line.strip()[:120],
                        "context": "\n".join(lines[max(0,i-1):i+2]),
                    })
    return entries


def generate_retrospective(code, name):
    """对某只股票过去所有建议做复盘"""
    entries = analyze_stock_timeline(code)
    if not entries:
        return None
    
    result = {
        "code": code,
        "name": name,
        "entry_count": len(entries),
        "first_seen": entries[0]["time"],
        "last_seen": entries[-1]["time"],
        "timeline": entries,
    }
    return result


def identify_gaps():
    """识别知微的分析gap"""
    reports = load_reports()
    gaps = []
    
    # Gap 1: 缺少止盈建议（对比止损）
    stop_loss_count = 0
    take_profit_count = 0
    for r in reports:
        c = r.get("content", "")
        stop_loss_count += c.count("止损")
        take_profit_count += c.count("止盈")
    
    gap_ratio = stop_loss_count / max(take_profit_count, 1)
    if gap_ratio > 3:
        gaps.append(f"止损共{stop_loss_count}次，止盈仅{take_profit_count}次，比例{gap_ratio:.1f}:1。止盈意识不足，应增加止盈建议频率")
    
    # Gap 2: 模糊用词过多
    vague_words = ["关注", "观望", "留意", "观察", "考虑"]
    vague_count = sum(sum(r.get("content", "").count(w) for r in reports) for w in vague_words)
    if vague_count > 30:
        gaps.append(f"模糊用词（关注/观望/留意等）共{vague_count}次，应减少，改用具体动作+价格")
    
    # Gap 3: 跨报告连贯性
    all_codes = set()
    for r in reports:
        codes = re.findall(r'\b\d{5,6}\b', r.get("content", ""))
        all_codes.update(codes)
    
    for code in list(all_codes)[:5]:
        entries = analyze_stock_timeline(code)
        action_count = len(entries)
        if action_count > 3:
            gaps.append(f"{code}出现{action_count}次，没有跟踪验证之前的建议是否有效")
    
    return gaps


if __name__ == "__main__":
    print("=" * 60)
    print("📋 知微复盘报告")
    print(f"   生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M')}")
    print("=" * 60)
    
    gaps = identify_gaps()
    print(f"\n🔍 发现 {len(gaps)} 个改进点:")
    for g in gaps:
        print(f"  ⚠️  {g}")
    
    print("\n📈 个股跟踪示例:")
    for code, name in [("688411", "海博思创"), ("600563", "法拉电子"), ("600110", "诺德股份")]:
        retro = generate_retrospective(code, name)
        if retro:
            print(f"\n  {name}({code}): {retro['entry_count']}次提及")
            for e in retro["timeline"][-3:]:
                print(f"    [{e['time'][:16]}] {e['line']}")
    
    print("\n✅ 复盘完成")