#!/usr/bin/env python3
"""
매일 지정 시각(기본 19:00 KST) 최근 24시간 수익률 텔레그램 발송.

사용:
  python scripts/07_daily_pnl_telegram.py --once      # 즉시 1회 발송
  python scripts/07_daily_pnl_telegram.py             # 스케줄 루프 (상시)
  python scripts/07_daily_pnl_telegram.py --record    # 스냅샷만 기록

Windows 작업 스케줄러: 매일 19:00에 --once 실행도 가능.
"""

from __future__ import annotations

import argparse
import runpy
import sys
from pathlib import Path

runpy.run_path(str(Path(__file__).resolve().parent / "_bootstrap.py"))

from config import (  # noqa: E402
    DAILY_PNL_REPORT_ENABLED,
    DAILY_PNL_REPORT_HOUR,
    DAILY_PNL_REPORT_MINUTE,
    DAILY_PNL_REPORT_TZ,
)
from deepcoin.ops.monitor import Monitor  # noqa: E402
from deepcoin.ops.portfolio_report import (  # noqa: E402
    append_portfolio_snapshot,
    fetch_portfolio_snapshot,
    run_schedule_loop,
    send_daily_pnl_report,
)


def main() -> int:
    """
    CLI 진입점.

    Returns:
        0 성공, 1 비활성/오류.
    """
    parser = argparse.ArgumentParser(description="일일 24h 수익률 텔레그램")
    parser.add_argument(
        "--once",
        action="store_true",
        help="즉시 1회 발송 후 종료",
    )
    parser.add_argument(
        "--record",
        action="store_true",
        help="스냅샷만 기록 (텔레그램 없음)",
    )
    args = parser.parse_args()

    if not DAILY_PNL_REPORT_ENABLED:
        print("DAILY_PNL_REPORT_ENABLED=0 — 종료")
        return 1

    print(
        f"[07] DAILY_PNL · {DAILY_PNL_REPORT_HOUR:02d}:"
        f"{DAILY_PNL_REPORT_MINUTE:02d} {DAILY_PNL_REPORT_TZ}"
    )
    mon = Monitor(cooldown_file=None)

    if args.record:
        snap = fetch_portfolio_snapshot(mon)
        append_portfolio_snapshot(snap)
        print(f"[07] snapshot total=₩{snap['total_asset_krw']:,.0f}")
        return 0

    if args.once:
        send_daily_pnl_report(mon)
        return 0

    run_schedule_loop(mon)
    return 0


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