"""Register with Claude Code."""

from pathlib import Path
import subprocess


def register_claude_code(project_level: bool = True) -> bool:
    """Register as Claude Code skill.

    Args:
        project_level: If True (default), register to project-level .claude/multi-lang-build.md.
                      If False, register to global ~/.claude/CLAUDE.md.
    """
    try:
        # Determine registration path
        if project_level:
            # Project-level: .claude/multi-lang-build.md in current directory
            config_dir = Path.cwd() / ".claude"
            config_dir.mkdir(exist_ok=True)
            skill_file = config_dir / "multi-lang-build.md"
            level_name = "project-level"
        else:
            # Global-level: ~/.claude/CLAUDE.md (only check CLI for global)
            result = subprocess.run(
                ["which", "claude"],
                capture_output=True,
                text=True,
            )

            if result.returncode != 0:
                print("❌ Claude Code CLI not found. Please install it first:")
                print("   npm install -g @anthropic-ai/claude-code")
                return False

            claude_dir = Path.home() / ".claude"
            claude_dir.mkdir(exist_ok=True)
            skill_file = claude_dir / "CLAUDE.md"
            level_name = "global"

        skill_content = """## Multi-Lang Build Tool

You can use the `multi-lang-build` tool to compile projects:

### Available Commands:
- `multi-lang-build pnpm <source> --output <dir>` - Build pnpm projects
- `multi-lang-build go <source> --output <bin>` - Build Go projects
- `multi-lang-build python <source> --output <dir>` - Build Python projects
- `multi-lang-build mirror list|set|show` - Configure domestic mirrors

### Examples:
```bash
# Build Go project
multi-lang-build go ./src --output ./bin/app --mirror

# Build with specific target (multi-entry support)
multi-lang-build go ./src --output ./bin/server --target ./cmd/server

# Build Python project
multi-lang-build python ./src --output ./dist --mirror

# Build pnpm project
multi-lang-build pnpm ./src --output ./dist --mirror

# Configure mirror
multi-lang-build mirror set pip pip_aliyun
multi-lang-build mirror set go
```

When working with Go projects, check if there are multiple main packages and use the `--target` flag to specify which one to build.
"""

        if project_level:
            # Project-level: create dedicated file
            with open(skill_file, "w") as f:
                f.write(skill_content)
            print(f"✅ Registered with Claude Code ({level_name}, created {skill_file})")
        else:
            # Global-level: append to existing CLAUDE.md if not already present
            existing_content = ""
            if skill_file.exists():
                existing_content = skill_file.read_text()

            if "## Multi-Lang Build Tool" not in existing_content:
                with open(skill_file, "a") as f:
                    f.write(skill_content)
                print(f"✅ Registered with Claude Code ({level_name}, added to {skill_file})")
            else:
                print(f"ℹ️ Already registered with Claude Code ({level_name}, {skill_file})")

        return True

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