#!/usr/bin/env python3
"""refresh_macro_context.py — 刷新macro_context_log

读取最新market_snapshots + 腾讯实时指数, 写入macro_context_log
让load_macro_context()拿到最新市场偏向, 而不是12天前的数据

每30分钟跑一次（交易日）
"""
import json, sqlite3, sys
from pathlib import Path
from datetime import datetime
from mo_data import get_price

DB = Path("/home/hmo/MoFin/data/mofin.db")

def fetch_index(code, name):
    """从统一入口获取指数行情"""
    try:
        price, change_pct = get_price(code)
        if price is not None:
            return {
                "price": price,
                "change_pct": round(change_pct or 0, 2),
                "high": price,
                "low": price,
            }
        return None
    except:
        return None

def main():
    # 采集各指数
    indices = {
        "上证指数": fetch_index("sh000001", "上证指数"),
        "深证成指": fetch_index("sz399001", "深证成指"),
        "创业板指": fetch_index("sz399006", "创业板指"),
        "恒生指数": fetch_index("szHSI", "恒生指数"),
        "国企指数": fetch_index("szHSCEI", "国企指数"),
    }
    indices = {k: v for k, v in indices.items() if v}

    # 计算偏向
    sh = indices.get("上证指数", {})
    sh_change = sh.get("change_pct", 0) if sh else 0
    if sh_change < -1.5:
        overall = "bearish"
        desc = "大盘偏弱"
    elif sh_change > 1.0:
        overall = "bullish"
        desc = "大盘偏强"
    else:
        overall = "neutral"
        desc = "大盘震荡"

    structure = json.dumps({"overall": overall, "description": desc}, ensure_ascii=False)
    indices_json = json.dumps(indices, ensure_ascii=False)

    # 写入macro_context_log
    now = datetime.now()
    session = "midday" if now.hour >= 12 else "morning"
    ts = now.strftime("%Y-%m-%d %H:%M:%S")
    try:
        conn = sqlite3.connect(str(DB))
        conn.execute("""
            INSERT INTO macro_context_log 
            (data_timestamp, session, has_valid_data, indices, structure, created_at)
            VALUES (?, ?, 1, ?, ?, ?)
        """, (ts, session, indices_json, structure, ts))
        conn.commit()
        conn.close()
        print(f"[SILENT] macro_context updated: {overall} {desc} {len(indices)} indices")
    except Exception as e:
        print(f"[SILENT] macro_context write failed: {e}")

if __name__ == "__main__":
    main()
