"""
04 산출 matched_rules.json 로드.
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

from deepcoin.paths import MATCHING_MATCHED_RULES


def load_matched_rules(path: Path | None = None) -> dict[str, Any]:
    """
    matched_rules.json 전체를 로드합니다.

    Args:
        path: JSON 경로. None이면 기본 경로.

    Returns:
        matched_rules dict. 없으면 빈 dict.
    """
    p = path or MATCHING_MATCHED_RULES
    if not p.is_file():
        return {}
    return json.loads(p.read_text(encoding="utf-8"))


def load_active_rules(path: Path | None = None) -> list[dict[str, Any]]:
    """
    04 선별 규칙 전체(strict 우선).

    Args:
        path: matched_rules.json 경로.

    Returns:
        규칙 dict 리스트.
    """
    data = load_matched_rules(path)
    selected = data.get("selected") or []
    if selected:
        return list(selected)
    return list(data.get("selected_best_effort") or [])


def load_monitor_rules(path: Path | None = None) -> list[dict[str, Any]]:
    """
    05 모니터·텔레그램에 쓸 규칙 (holdout 통과, 매수·매도 각 최대 1개).

    Args:
        path: matched_rules.json 경로.

    Returns:
        monitor_rules 또는 active_rules fallback.
    """
    data = load_matched_rules(path)
    monitor = data.get("monitor_rules") or []
    if monitor:
        return list(monitor)
    return load_active_rules(path)
