#!/usr/bin/env python3
"""inject_xiaoguo_insight.py — 将小果情感分析结果注入 market.json

时序：market_watch(15:30) → market_insight(15:35) → xiaoguo_analyst(16:00) → 本脚本(16:05)

读取 xiaoguo_insights.json 的情感分析结果，注入到 market.json 的 insights 字段
"""

import json
from datetime import datetime
from pathlib import Path

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


def inject():
    market_path = DATA_DIR / "market.json"
    xiaoguo_path = DATA_DIR / "xiaoguo_insights.json"

    if not xiaoguo_path.exists():
        print("xiaoguo_insights.json 不存在，跳过")
        return

    with open(xiaoguo_path, "r", encoding="utf-8") as f:
        xiaoguo = json.load(f)

    analyses = xiaoguo.get("analyses", [])
    if not analyses:
        print("小果分析为空，跳过")
        return

    with open(market_path, "r", encoding="utf-8") as f:
        market = json.load(f)

    insights = market.get("insights", [])

    # 注入情感分析结果
    for a in analyses:
        name = a.get("name", "")
        sentiment = a.get("sentiment", "neutral")
        confidence = a.get("confidence", 0)
        brief = a.get("brief", "")
        sentiment_emoji = {"positive": "", "negative": "", "neutral": ""}.get(
            sentiment, ""
        )
        label = {"positive": "利好", "negative": "利空", "neutral": "中性"}.get(
            sentiment, "中性"
        )

        if brief:
            insights.append(
                f"[小果]{name}: {label}(置信度{confidence:.0%}) — {brief}"
            )

    market["insights"] = insights
    market["xiaoguo_timestamp"] = xiaoguo.get("timestamp", "")

    with open(market_path, "w", encoding="utf-8") as f:
        json.dump(market, f, ensure_ascii=False, indent=2)

    print(f"注入{len(analyses)}条小果分析到 market.json")


if __name__ == "__main__":
    inject()
