"""engine_v2/cost_tracker.py — JSONL append-only 비용 추적."""

from __future__ import annotations

import json
from datetime import datetime, timezone
from pathlib import Path

try:
    import yaml as _yaml_mod

    _YAML_AVAILABLE = True
except ImportError:
    _yaml_mod = None  # type: ignore[assignment]
    _YAML_AVAILABLE = False

from engine_v2.engine_result import EngineResult

_LOG_DIR = Path("/home/jay/workspace/memory")
_BUDGET_PATH = Path("/home/jay/workspace/config/engine_budget.yaml")


def _get_log_path() -> Path:
    """월별 파일 경로 반환."""
    now = datetime.now(timezone.utc)
    filename = f"engine_usage_{now.strftime('%Y-%m')}.jsonl"
    return _LOG_DIR / filename


def log_usage(result: EngineResult, prompt_chars: int, duration_sec: float) -> None:
    """사용량 기록 (JSONL append)."""
    entry = {
        "ts": datetime.now(timezone.utc).isoformat(),
        "task_id": result.task_id,
        "step": result.step,
        "engine": result.engine,
        "prompt_chars": prompt_chars,
        "output_chars": len(result.content),
        "token_est": result.token_est,
        "fallback_used": result.fallback_used,
        "flagged_count": result.flagged_count,
        "duration_sec": round(duration_sec, 2),
        "error": result.error,
    }
    log_path = _get_log_path()
    log_path.parent.mkdir(parents=True, exist_ok=True)
    with open(log_path, "a", encoding="utf-8") as f:
        f.write(json.dumps(entry, ensure_ascii=False) + "\n")


def _load_budget() -> dict[str, object]:
    """config/engine_budget.yaml을 읽어 daily_limits를 반환.

    yaml 파일이 없거나 읽기 실패 시 빈 dict 반환 (한도 무제한).
    """
    if not _BUDGET_PATH.exists():
        return {}
    try:
        if _YAML_AVAILABLE and _yaml_mod is not None:
            with open(_BUDGET_PATH, "r", encoding="utf-8") as f:
                data = _yaml_mod.safe_load(f)
        else:
            # PyYAML 미설치 시 JSON 대안 없음 — 한도 무제한으로 fallback
            return {}
        if not isinstance(data, dict):
            return {}
        limits = data.get("daily_limits", {})
        return limits if isinstance(limits, dict) else {}
    except Exception:
        return {}


def check_budget(engine: str) -> bool:
    """오늘의 엔진 호출 수가 일일 한도를 초과했는지 확인.

    Args:
        engine: 확인할 엔진 이름 ("claude", "gemini", "codex" 등)

    Returns:
        True이면 한도 초과 (차단 필요), False이면 허용.
    """
    daily_limits = _load_budget()
    if not daily_limits:
        return False  # yaml 없음 → 한도 무제한

    engine_limit = daily_limits.get(engine)
    if not isinstance(engine_limit, dict):
        return False  # 해당 엔진 설정 없음 → 허용

    max_calls = engine_limit.get("max_calls")
    if not isinstance(max_calls, int):
        return False  # max_calls 설정 없음 → 허용

    # 현재 월의 JSONL 파일에서 오늘 날짜의 해당 engine 호출 수 집계
    now = datetime.now(timezone.utc)
    today_str = now.strftime("%Y-%m-%d")
    year_month = now.strftime("%Y-%m")

    entries = read_usage(year_month)
    call_count = sum(
        1
        for entry in entries
        if entry.get("engine") == engine
        and isinstance(entry.get("ts"), str)
        and entry["ts"].startswith(today_str)  # type: ignore[union-attr]
    )

    return call_count >= max_calls


def read_usage(year_month: str | None = None) -> list[dict[str, object]]:
    """사용량 읽기."""
    if year_month is None:
        now = datetime.now(timezone.utc)
        year_month = now.strftime("%Y-%m")
    log_path = _LOG_DIR / f"engine_usage_{year_month}.jsonl"
    if not log_path.exists():
        return []
    entries: list[dict[str, object]] = []
    with open(log_path, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line:
                entries.append(json.loads(line))
    return entries
