"""pinn virtual persona 上云 stub — users/pinn/virtual_personas → persist mirror。"""

from __future__ import annotations

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

from niannian.users.paths import virtual_personas_root
from niannian.virtual_persona.store import VirtualPersonaStore, _sanitize_vp_id


def vp_cloud_mirror_root(home: Path) -> Path:
    return Path(home) / "persist" / "vp_cloud_mirror"


def sync_virtual_persona_to_cloud(
    home: Path,
    vp_id: str,
    *,
    user_id: str = "pinn",
) -> dict[str, Any]:
    """同步 users/{user_id}/virtual_personas/{vp_id}/ 至本地 cloud mirror。"""
    uid = str(user_id).strip() or "pinn"
    if uid != "pinn":
        raise ValueError("virtual persona cloud_sync is pinn-only")
    vid = _sanitize_vp_id(vp_id)
    store = VirtualPersonaStore(home, uid)
    src = store.export_bundle(vid)
    mirror = vp_cloud_mirror_root(home) / "users" / uid / "virtual_personas" / vid
    mirror.parent.mkdir(parents=True, exist_ok=True)
    shutil.copytree(src, mirror, dirs_exist_ok=True)
    store.set_storage_tier(vid, "cloud")
    synced_at = datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
    return {
        "username": uid,
        "vp_id": vid,
        "synced_at": synced_at,
        "vp_mirror": str(mirror),
        "remote_path": f"remote/users/{uid}/virtual_personas/{vid}/",
        "storage_tier": "cloud",
    }


def sync_all_virtual_personas_to_cloud(home: Path, *, user_id: str = "pinn") -> dict[str, Any]:
    uid = str(user_id).strip() or "pinn"
    if uid != "pinn":
        raise ValueError("virtual persona cloud_sync is pinn-only")
    root = virtual_personas_root(home, uid)
    synced: list[str] = []
    if root.is_dir():
        for child in sorted(root.iterdir()):
            if child.is_dir() and (child / "meta.yaml").is_file():
                sync_virtual_persona_to_cloud(home, child.name, user_id=uid)
                synced.append(child.name)
    synced_at = datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
    return {
        "username": uid,
        "synced_at": synced_at,
        "vp_ids": synced,
        "remote_root": f"remote/users/{uid}/virtual_personas/",
    }
