"""Register with OpenCode."""

import json
from pathlib import Path


def register_opencode(project_level: bool = True) -> bool:
    """Register as OpenCode skill.

    Args:
        project_level: If True (default), register to project-level .opencode/skills.json.
                      If False, register to global ~/.config/opencode/skills.json.
    """
    try:
        # Determine registration path
        if project_level:
            # Project-level: .opencode/skills.json in current directory
            base_dir = Path.cwd()
            config_dir = base_dir / ".opencode"
            config_dir.mkdir(exist_ok=True)
            skills_file = config_dir / "skills.json"
            level_name = "project-level"
        else:
            # Global-level: ~/.config/opencode/skills.json
            config_dir = Path.home() / ".config" / "opencode"
            config_dir.mkdir(parents=True, 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": "Multi-language automated build tool with mirror acceleration",
            "commands": {
                "build-go": "multi-lang-build go <source> --output <output> [--mirror] [--target <target>]",
                "build-python": "multi-lang-build python <source> --output <output> [--mirror]",
                "build-pnpm": "multi-lang-build pnpm <source> --output <output> [--mirror]",
            },
            "examples": [
                "multi-lang-build go ./src --output ./bin/app --mirror",
                "multi-lang-build go ./src --output ./bin/server --target ./cmd/server",
                "multi-lang-build python ./src --output ./dist --mirror",
                "multi-lang-build pnpm ./src --output ./dist --mirror",
            ]
        }

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

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

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