"""
Luu trang thai phien chay hien tai de tiep tuc neu bi gian doan.
File: ~/.sora-tool/session.json
"""
from __future__ import annotations

import json
import threading
from datetime import datetime

_FILE_LOCK = threading.Lock()

from .constants import APP_DATA_DIR

_SESSION_FILE = APP_DATA_DIR / "session.json"

PENDING  = "pending"
DONE     = "done"
FAILED   = "failed"


def _read() -> dict | None:
    if not _SESSION_FILE.exists():
        return None
    try:
        return json.loads(_SESSION_FILE.read_text(encoding="utf-8"))
    except Exception:
        return None


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


def create_session(batches_data: list[dict]) -> None:
    """Tao phien moi. batches_data la list cac dict voi keys: profile_id, alias, products."""
    with _FILE_LOCK:
        _write({
            "started_at": datetime.now().isoformat(),
            "status": "in_progress",
            "batches": batches_data,
        })


def load_session() -> dict | None:
    with _FILE_LOCK:
        return _read()


def has_active_session() -> bool:
    s = load_session()
    return s is not None and s.get("status") == "in_progress"


def update_product_status(profile_id: str, product_id, status: str) -> None:
    with _FILE_LOCK:
        s = _read()
        if not s:
            return
        for batch in s["batches"]:
            if batch["profile_id"] == profile_id:
                for p in batch["products"]:
                    if p["id"] == product_id:
                        p["status"] = status
                        break
                break
        _write(s)


def mark_session_done() -> None:
    with _FILE_LOCK:
        s = _read()
        if not s:
            return
        s["status"] = "done"
        _write(s)


def clear_session() -> None:
    with _FILE_LOCK:
        if _SESSION_FILE.exists():
            _SESSION_FILE.unlink()
