"""pinn persona 上云 stub — users/pinn/persona → persist mirror（Docker only）。"""

from __future__ import annotations

import shutil
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

from niannian.users.paths import objects_root, persona_dir


def persona_cloud_mirror_root(home: Path) -> Path:
    return Path(home) / "persist" / "persona_cloud_mirror"


def sync_persona_to_cloud(
    home: Path,
    user_id: str = "pinn",
    *,
    include_objects: bool = False,
) -> dict[str, Any]:
    """同步 users/{user_id}/persona/ 至本地 cloud mirror（remote/users/{user_id}/persona/ 语义）。"""
    uid = str(user_id).strip() or "pinn"
    if uid != "pinn":
        raise ValueError("persona cloud_sync is pinn-only")

    src_persona = persona_dir(home, uid)
    if not src_persona.is_dir():
        raise FileNotFoundError(f"persona dir missing: {src_persona}")

    mirror = persona_cloud_mirror_root(home) / "users" / uid / "persona"
    mirror.parent.mkdir(parents=True, exist_ok=True)
    shutil.copytree(src_persona, mirror, dirs_exist_ok=True)

    objects_synced = False
    if include_objects:
        src_objects = objects_root(home, uid)
        if src_objects.is_dir():
            dest_objects = persona_cloud_mirror_root(home) / "users" / uid / "objects"
            shutil.copytree(src_objects, dest_objects, dirs_exist_ok=True)
            objects_synced = True

    synced_at = datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
    return {
        "username": uid,
        "synced_at": synced_at,
        "persona_mirror": str(mirror),
        "remote_path": f"remote/users/{uid}/persona/",
        "objects_synced": objects_synced,
    }
