[CmdletBinding()]
param()

$ErrorActionPreference = 'Stop'
$SkillId = 'mml-parser-zhiyisoft'
$CodeBuddyRoot = Join-Path $HOME '.codebuddy\skills-marketplace\skills'
$Target = Join-Path $CodeBuddyRoot $SkillId
$HomePath = [System.IO.Path]::GetFullPath($HOME).TrimEnd('\') + '\'
$TargetPath = [System.IO.Path]::GetFullPath($Target)

if (-not $TargetPath.StartsWith($HomePath, [System.StringComparison]::OrdinalIgnoreCase)) {
    throw "Refusing to install outside the current user profile: $TargetPath"
}
if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot 'SKILL.md') -PathType Leaf)) {
    throw 'Invalid Skill package: SKILL.md must be at the package root.'
}

New-Item -ItemType Directory -Path $CodeBuddyRoot -Force | Out-Null
if (Test-Path -LiteralPath $Target) {
    $Backup = "$Target.backup-$(Get-Date -Format 'yyyyMMddHHmmss')"
    Move-Item -LiteralPath $Target -Destination $Backup
    Write-Host "Backed up previous Skill to: $Backup" -ForegroundColor Yellow
}
New-Item -ItemType Directory -Path $Target -Force | Out-Null
Get-ChildItem -LiteralPath $PSScriptRoot -Force | ForEach-Object {
    Copy-Item -LiteralPath $_.FullName -Destination $Target -Recurse -Force
}

$InstalledSkill = Join-Path $Target 'SKILL.md'
$NestedSkill = Join-Path $Target "$SkillId\SKILL.md"
if (-not (Test-Path -LiteralPath $InstalledSkill -PathType Leaf)) {
    throw "CodeBuddy Skill installation failed: $InstalledSkill is missing."
}
if (Test-Path -LiteralPath $NestedSkill -PathType Leaf) {
    throw "CodeBuddy Skill installation is nested incorrectly: $NestedSkill"
}

Write-Host "Installed CodeBuddy Skill 1.3.8: $InstalledSkill" -ForegroundColor Green
Write-Host 'Restart CodeBuddy, then use mml_status before starting a parse job.'
