#!/usr/bin/env python3
"""xiaoguo_sentiment_bridge.py — 小果情感分析数据 → 策略引擎桥接

小果情感分析 cron (3da7ad4ff3a6) 每日16:00运行，输出到指定格式。
本脚本读取小果的输出，格式化为 strategy_lifecycle 可读取的格式，
写入 /home/hmo/web-dashboard/data/xiaoguo_sentiment.json

格式：
{
  "updated_at": "2026-06-18T16:00:00",
  "stocks": {
    "00700": {
      "name": "腾讯控股",
      "sentiment": "positive" | "negative" | "neutral",
      "confidence": 0.85,
      "keywords": ["游戏", "增长"],
      "summary": "腾讯游戏业务Q2增长超预期",
      "source": "xiaoguo"
    }
  }
}
"""

import json
import os
import sys
from datetime import datetime

OUTPUT_PATH = "/home/hmo/web-dashboard/data/xiaoguo_sentiment.json"
XIAOGUO_INSIGHTS_PATH = "/home/hmo/web-dashboard/data/xiaoguo_insights.json"


def load_xiaoguo_output():
    """读取小果情感分析的最新输出"""
    try:
        if os.path.exists(XIAOGUO_INSIGHTS_PATH):
            with open(XIAOGUO_INSIGHTS_PATH) as f:
                data = json.load(f)
            return data
    except Exception:
        pass
    return None


def main():
    data = load_xiaoguo_output()
    if data is None:
        data = {"updated_at": datetime.now().isoformat(), "stocks": {}}
    else:
        # 转换为 {code: {sentiment, confidence, keywords, summary}} 格式
        formatted = {"updated_at": datetime.now().isoformat(), "stocks": {}}
        for item in data.get("analyses", []):
            code = item.get("code", "")
            if code:
                formatted["stocks"][code] = {
                    "name": item.get("name", ""),
                    "sentiment": item.get("sentiment", "neutral"),
                    "confidence": item.get("confidence", 0),
                    "keywords": item.get("keywords", []),
                    "summary": item.get("brief", ""),
                    "source": "xiaoguo",
                }
        data = formatted

    os.makedirs(os.path.dirname(OUTPUT_PATH), exist_ok=True)
    with open(OUTPUT_PATH, "w") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

    stock_count = len(data.get("stocks", {}))
    print(f"[xiaoguo_bridge] {stock_count} stocks synced", file=sys.stderr)


if __name__ == "__main__":
    main()
