"""Register with Trae."""

import json
from pathlib import Path


def register_trae(project_level: bool = True) -> bool:
    """Register as Trae skill.

    Args:
        project_level: If True (default), register to project-level .trae/skills.json.
                      If False, register to global ~/.trae/skills.json.
    """
    try:
        # Determine registration path
        if project_level:
            # Project-level: .trae/skills.json in current directory
            base_dir = Path.cwd()
            config_dir = base_dir / ".trae"
            config_dir.mkdir(exist_ok=True)
            skills_file = config_dir / "skills.json"
            level_name = "project-level"
        else:
            # Global-level: ~/.trae/skills.json
            config_dir = Path.home() / ".trae"
            config_dir.mkdir(exist_ok=True)
            skills_file = config_dir / "skills.json"
            level_name = "global"

        # Create or update skills.json
        skills: dict = {}

        if skills_file.exists():
            with open(skills_file) as f:
                skills = json.load(f)

        # Add multi-lang-build skill
        skills["multi-lang-build"] = {
            "name": "Multi-Lang Build",
            "description": "Automated build tool for Go, Python, and pnpm projects",
            "category": "build",
            "commands": [
                {
                    "name": "build-go",
                    "command": "multi-lang-build go {source} --output {output}",
                    "description": "Build Go project",
                    "args": ["source", "output", "target", "mirror"]
                },
                {
                    "name": "build-python",
                    "command": "multi-lang-build python {source} --output {output}",
                    "description": "Build Python project",
                    "args": ["source", "output", "mirror"]
                },
                {
                    "name": "build-pnpm",
                    "command": "multi-lang-build pnpm {source} --output {output}",
                    "description": "Build pnpm project",
                    "args": ["source", "output", "mirror"]
                }
            ]
        }

        with open(skills_file, "w") as f:
            json.dump(skills, f, indent=2)

        print(f"✅ Registered with Trae ({level_name}, config: {skills_file})")
        return True

    except Exception as e:
        print(f"❌ Failed to register with Trae: {e}")
        return False
