#!/usr/bin/env python3
"""
Refresh Today Trades snapshot from a JSON book config (for VPS cron).

::

    cd /path/to/trading_bot
    .venv/bin/python -m RenTech.monitor.refresh_today_trades \\
      --config RenTech/monitor/config/today_trades_book.json

Cron example (weekdays 9:40 America/New_York — set TZ on the host or use UTC)::

    40 13 * * 1-5 cd /path/to/trading_bot && .venv/bin/python -m RenTech.monitor.refresh_today_trades >> RenTech/data/logs/today_trades_cron.log 2>&1
"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

_REPO = Path(__file__).resolve().parents[2]
if str(_REPO) not in sys.path:
    sys.path.insert(0, str(_REPO))

from RenTech.monitor.build_today_trades_snapshot import (  # noqa: E402
    DEFAULT_OUT,
    DEFAULT_STATE,
    _held_from_args_and_state,
    _load_state,
    build_snapshot,
)

DEFAULT_CONFIG = _REPO / "RenTech" / "monitor" / "config" / "today_trades_book.json"


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    ap.add_argument("--config", type=Path, default=DEFAULT_CONFIG)
    args = ap.parse_args()

    cfg_path = args.config.expanduser()
    if not cfg_path.is_absolute():
        cfg_path = (_REPO / cfg_path).resolve()
    raw = json.loads(cfg_path.read_text(encoding="utf-8"))

    held_list = raw.get("held") or []
    held_csv = ",".join(str(x).upper() for x in held_list)
    state_path = Path(str(raw.get("state") or DEFAULT_STATE))
    if not state_path.is_absolute():
        state_path = (_REPO / state_path).resolve()
    out = Path(str(raw.get("out") or DEFAULT_OUT))
    if not out.is_absolute():
        out = (_REPO / out).resolve()

    state = _load_state(state_path)
    held = _held_from_args_and_state(held_csv or None, state)
    approx = raw.get("approx_per_name_mv")
    snap = build_snapshot(
        account_id=str(raw.get("account_id", "demo")),
        label=str(raw.get("label", "Stock-only book")),
        nav=float(raw.get("nav_usd", 50_000)),
        fund_scale=float(raw.get("fund_scale", 1.5)),
        held=held,
        spy_proxy=str(raw.get("spy_proxy", "VOO")),
        approx_per_name_mv=float(approx) if approx not in (None, 0, 0.0) else None,
        skip_new_entries=bool(raw.get("skip_new_entries", False)),
    )
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(json.dumps(snap, indent=2) + "\n", encoding="utf-8")

    book = snap["books"][0]
    print(
        json.dumps(
            {
                "ok": True,
                "out": str(out),
                "config": str(cfg_path),
                "as_of_date": book["as_of_date"],
                "n_exit": len(book["trades"]["exit"]),
                "n_enter": len(book["trades"]["enter"]),
                "n_hold": len(book["trades"]["hold"]),
                "held": sorted(held),
            },
            indent=2,
        )
    )


if __name__ == "__main__":
    main()
