#!/usr/bin/env python3
"""
MiniMax 资源注册脚本
生成文件后自动注册到 __MY_ARTIFACTS__.json

用法:
  AUTO_REGISTRY=true ./image.sh "描述"
  AUTO_REGISTRY=false ./image.sh "描述"   # 不注册

环境变量:
  WORKSPACE_NAME  - workspace名称，main 或其他
  AUTO_REGISTRY   - true=注册到JSON, false=不注册
  MINIMAX_API_KEY - API密钥（不需要，生成用）
"""

import os
import json
import sys

# 添加 server 目录到 path 以导入共享模块
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', 'server'))
from artifacts_schema import ARTIFACTS_FILENAME, create_empty_artifacts, now_iso

WORKSPACE = os.environ.get("WORKSPACE_NAME", "main")
AUTO_REGISTRY = os.environ.get("AUTO_REGISTRY", "false").lower() == "true"

OPENCLAW_HOME = os.environ.get("OPENCLAW_HOME", os.path.join(os.path.expanduser("~"), ".openclaw"))

# 路径构建
if WORKSPACE == "main":
    WORKSPACE_ROOT = os.path.join(OPENCLAW_HOME, "workspace")
else:
    WORKSPACE_ROOT = os.path.join(OPENCLAW_HOME, f"workspace-{WORKSPACE}")

MYCLAW_DIR = os.path.join(WORKSPACE_ROOT, ".myclaw")
REGISTRY_FILE = os.path.join(MYCLAW_DIR, ARTIFACTS_FILENAME)

# registry 的 base_url（远程服务端 API）
REGISTRY_BASE_URL = "https://claw.kekouen.cn/cmd/api/preview?path="


def load_registry():
    """加载或初始化 registry"""
    if os.path.exists(REGISTRY_FILE):
        with open(REGISTRY_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    return create_empty_artifacts(WORKSPACE, REGISTRY_BASE_URL)


def save_registry(data):
    """保存 registry"""
    os.makedirs(MYCLAW_DIR, exist_ok=True)
    data["updated_at"] = now_iso()
    with open(REGISTRY_FILE, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)


def guess_type(filename):
    """根据扩展名判断资源类型"""
    ext = os.path.splitext(filename)[1].lower()
    type_map = {
        ".png": "image", ".jpg": "image", ".jpeg": "image",
        ".gif": "image", ".webp": "image", ".bmp": "image",
        ".mp4": "video", ".mov": "video", ".avi": "video",
        ".mp3": "audio", ".wav": "audio", ".flac": "audio",
        ".html": "html", ".htm": "html",
        ".pdf": "document", ".doc": "document", ".docx": "document",
    }
    return type_map.get(ext, "file")


def register_asset(filepath, name=None):
    """
    注册一个文件到 JSON
    filepath: 完整路径，如 /root/.openclaw/workspace/media/image_xxx.png
    """
    if not AUTO_REGISTRY:
        print(f"[Registry] AUTO_REGISTRY=false，跳过注册")
        return

    filename = os.path.basename(filepath)
    rel_path = os.path.relpath(filepath, WORKSPACE_ROOT)
    asset_type = guess_type(filename)

    # 生成 id
    import hashlib
    asset_id = hashlib.md5(filename.encode()).hexdigest()[:8]
    asset_id = f"asset-{asset_id}"

    # 生成 name
    if not name:
        name = os.path.splitext(filename)[0]

    registry = load_registry()

    # 检查是否已存在（同名文件）
    for i, asset in enumerate(registry["assets"]):
        if asset.get("path") == rel_path:
            registry["assets"][i] = {
                "id": asset_id,
                "type": asset_type,
                "name": name,
                "path": rel_path
            }
            save_registry(registry)
            print(f"[Registry] 已更新: {rel_path}")
            return

    # 新增
    registry["assets"].append({
        "id": asset_id,
        "type": asset_type,
        "name": name,
        "path": rel_path
    })
    save_registry(registry)
    print(f"[Registry] 已注册: {rel_path} ({asset_type})")


if __name__ == "__main__":
    # CLI 模式
    if len(sys.argv) < 2:
        print(f"用法: AUTO_REGISTRY=true python3 registry.py <文件路径> [名称]")
        print(f"环境: WORKSPACE_NAME={WORKSPACE}, AUTO_REGISTRY={AUTO_REGISTRY}")
        sys.exit(1)

    filepath = sys.argv[1]
    name = sys.argv[2] if len(sys.argv) > 2 else None
    register_asset(filepath, name)
