"""
Theo doi lich su chay: profile nao da chay bao nhieu san pham, ngay nao.
Luu tai ~/.sora-tool/run_log.json
"""
from __future__ import annotations

import json
from datetime import date

from .constants import APP_DATA_DIR

_LOG_FILE = APP_DATA_DIR / "run_log.json"


def _load() -> dict:
    if not _LOG_FILE.exists():
        return {}
    return json.loads(_LOG_FILE.read_text(encoding="utf-8"))


def _save(data: dict) -> None:
    APP_DATA_DIR.mkdir(parents=True, exist_ok=True)
    _LOG_FILE.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")


def _today_entry(profile_log: dict) -> dict:
    today = str(date.today())
    entry = next((r for r in profile_log["runs"] if r["date"] == today), None)
    if entry is None:
        entry = {"date": today, "done": 0, "failed": 0, "product_ids": []}
        profile_log["runs"].append(entry)
    return entry


def _profile_log(data: dict, profile_id: str) -> dict:
    if profile_id not in data:
        data[profile_id] = {"runs": [], "total_done": 0, "total_failed": 0}
    return data[profile_id]


def record_product_done(profile_id: str, product_id: int) -> None:
    data = _load()
    log = _profile_log(data, profile_id)
    entry = _today_entry(log)
    entry["done"] += 1
    entry["product_ids"].append(product_id)
    log["total_done"] += 1
    _save(data)


def record_product_failed(profile_id: str) -> None:
    data = _load()
    log = _profile_log(data, profile_id)
    entry = _today_entry(log)
    entry["failed"] += 1
    log["total_failed"] += 1
    _save(data)


def get_profile_stats(profile_id: str) -> dict:
    return _load().get(profile_id, {"runs": [], "total_done": 0, "total_failed": 0})
