"""
Ground Truth 매수·매도 시각표 (04-3 leg 라벨링용).
"""

from __future__ import annotations

from pathlib import Path
from typing import Any

import numpy as np
import pandas as pd

from deepcoin.ground_truth.ground_truth import load_ground_truth
from deepcoin.paths import resolve_ground_truth_file


def load_gt_trade_events(
    gt_path: Path | str | None = None,
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
    """
    GT trades에서 매수·매도 이벤트 시각(ns)·가격 배열을 만듭니다.

    Args:
        gt_path: ground_truth JSON 경로. None이면 기본 경로.

    Returns:
        (buy_ts_ns, buy_px, sell_ts_ns, sell_px) 오름차순 정렬.
    """
    path = (
        resolve_ground_truth_file()
        if gt_path is None
        else Path(gt_path)
    )
    data = load_ground_truth(path) or {}
    trades: list[dict[str, Any]] = data.get("trades") or []

    buys: list[tuple[pd.Timestamp, float]] = []
    sells: list[tuple[pd.Timestamp, float]] = []
    for t in trades:
        ts = pd.Timestamp(t["dt"])
        px = float(t["price"])
        if t.get("action") == "buy":
            buys.append((ts, px))
        elif t.get("action") == "sell":
            sells.append((ts, px))

    buys.sort(key=lambda x: x[0])
    sells.sort(key=lambda x: x[0])

    if buys:
        buy_ts = np.array([x[0].value for x in buys], dtype=np.int64)
        buy_px = np.array([x[1] for x in buys], dtype=float)
    else:
        buy_ts = np.array([], dtype=np.int64)
        buy_px = np.array([], dtype=float)

    if sells:
        sell_ts = np.array([x[0].value for x in sells], dtype=np.int64)
        sell_px = np.array([x[1] for x in sells], dtype=float)
    else:
        sell_ts = np.array([], dtype=np.int64)
        sell_px = np.array([], dtype=float)

    return buy_ts, buy_px, sell_ts, sell_px
