"""프로젝트 meta.json 업서트."""
from __future__ import annotations

from pathlib import Path
from typing import Optional

from .json_boundary import load_owned_object, write_owned_object_atomic


def _project_meta_path(home: Path, project_id: str) -> Path:
    return home / "projects" / project_id / "meta.json"


def load_project_meta(home: Path, project_id: str) -> Optional[dict]:
    """프로젝트 meta.json 을 읽는다. 없으면 None."""
    p = _project_meta_path(home, project_id)
    if not p.is_file():
        return None
    return load_owned_object(p, artifact="project metadata")


def upsert_project_meta(home: Path, project_id: str, *,
                        project_root: str, when: str,
                        started: bool = False, finished: bool = False) -> None:
    """프로젝트 meta.json 을 read-modify-write 로 갱신.
    started=True 면 runCount+1, activeCount+1, lastRunAt 갱신, 최초이면 firstRunAt 도 설정.
    finished=True 면 activeCount-1, lastRunAt 갱신.
    """
    target = _project_meta_path(home, project_id)
    target.parent.mkdir(parents=True, exist_ok=True)
    if target.is_file():
        meta = load_owned_object(target, artifact="project metadata")
    else:
        meta = {
            "projectId": project_id,
            "projectRoot": project_root,
            "firstRunAt": when,
            "lastRunAt": when,
            "runCount": 0,
            "activeCount": 0,
        }
    meta["projectRoot"] = project_root
    meta["lastRunAt"] = when
    if started:
        meta["runCount"] = int(meta.get("runCount", 0)) + 1
        meta["activeCount"] = int(meta.get("activeCount", 0)) + 1
    if finished:
        meta["activeCount"] = max(0, int(meta.get("activeCount", 0)) - 1)
    write_owned_object_atomic(target, meta, artifact="project metadata")
