#!/usr/bin/env python3
"""Send the current dashboard summary to Kakao using the Keychain-aware sender."""

from __future__ import annotations

import argparse
import json
import subprocess
import sys
from pathlib import Path


ROOT = Path(__file__).resolve().parent
STATE_PATH = ROOT / "live_account_state.json"
SEND_SCRIPT = ROOT / "send_kakao_memo.py"


def build_message(state: dict) -> str:
    summary = state.get("kakao_summary", "").strip()
    flow = state.get("weekend_flow", {}).get("summary", "")
    leverage = state.get("single_stock_leverage", {})
    candidates = leverage.get("candidates", [])
    active = [x for x in candidates if x.get("status") != "대기"]
    active_text = ", ".join(f"{x['underlying']} {x['status']}" for x in active) or "대기"
    first_cash = leverage.get("first_trade_cash_required_krw", 10_000_000)

    lines = [summary] if summary else []
    if flow:
        lines.append(f"플로우: {flow}")
    lines.append(f"단일2배: {active_text} / 최초예수금 {first_cash/10000:,.0f}만원")
    lines.append(f"상태시각: {state.get('updated_at', '-')}")
    return "\n".join(lines)


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--title", default="US Equity 자동 요약")
    parser.add_argument("--dry-run", action="store_true")
    args = parser.parse_args()

    state = json.loads(STATE_PATH.read_text(encoding="utf-8"))
    message = build_message(state)
    command = ["python3", str(SEND_SCRIPT), "--title", args.title, "--message", message]
    if args.dry_run:
        command.append("--dry-run")

    result = subprocess.run(command, cwd=ROOT.parent, text=True, capture_output=True, check=False, timeout=60)
    print(result.stdout, end="")
    if result.returncode != 0:
        print(result.stderr, end="", file=sys.stderr)
    return result.returncode


if __name__ == "__main__":
    raise SystemExit(main())
