# mosaic-sync-skills.ps1
# Syncs canonical skills and links them into agent runtime skill directories.
# Uses directory junctions (no elevation required) with fallback to copies.
# PowerShell equivalent of mosaic-sync-skills (bash).
$ErrorActionPreference = "Stop"

param(
    [switch]$LinkOnly,
    [switch]$NoLink,
    [switch]$Help
)

$MosaicHome = if ($env:MOSAIC_HOME) { $env:MOSAIC_HOME } else { Join-Path $env:USERPROFILE ".config\mosaic" }
$SkillsRepoUrl = if ($env:MOSAIC_SKILLS_REPO_URL) { $env:MOSAIC_SKILLS_REPO_URL } else { "https://git.mosaicstack.dev/mosaic/agent-skills.git" }
$SkillsRepoDir = if ($env:MOSAIC_SKILLS_REPO_DIR) { $env:MOSAIC_SKILLS_REPO_DIR } else { Join-Path $MosaicHome "sources\agent-skills" }
$MosaicSkillsDir = Join-Path $MosaicHome "skills"
$MosaicLocalSkillsDir = Join-Path $MosaicHome "skills-local"

if ($Help) {
    Write-Host @"
Usage: mosaic-sync-skills.ps1 [-LinkOnly] [-NoLink] [-Help]

Sync canonical skills into ~/.config/mosaic/skills and link all Mosaic skills
into runtime skill directories using directory junctions.

Options:
  -LinkOnly     Skip git clone/pull and only relink
  -NoLink       Sync canonical skills but do not update runtime links
  -Help         Show help
"@
    exit 0
}

foreach ($d in @($MosaicHome, $MosaicSkillsDir, $MosaicLocalSkillsDir)) {
    if (-not (Test-Path $d)) { New-Item -ItemType Directory -Path $d -Force | Out-Null }
}

# Fetch skills from git
if (-not $LinkOnly) {
    if (Test-Path (Join-Path $SkillsRepoDir ".git")) {
        Write-Host "[mosaic-skills] Updating skills source: $SkillsRepoDir"
        git -C $SkillsRepoDir pull --rebase
    }
    else {
        Write-Host "[mosaic-skills] Cloning skills source to: $SkillsRepoDir"
        $parentDir = Split-Path $SkillsRepoDir -Parent
        if (-not (Test-Path $parentDir)) { New-Item -ItemType Directory -Path $parentDir -Force | Out-Null }
        git clone $SkillsRepoUrl $SkillsRepoDir
    }

    $sourceSkillsDir = Join-Path $SkillsRepoDir "skills"
    if (-not (Test-Path $sourceSkillsDir)) {
        Write-Host "[mosaic-skills] Missing source skills dir: $sourceSkillsDir" -ForegroundColor Red
        exit 1
    }

    # Sync: remove old, copy new
    if (Test-Path $MosaicSkillsDir) {
        Get-ChildItem $MosaicSkillsDir | Remove-Item -Recurse -Force
    }
    Copy-Item "$sourceSkillsDir\*" $MosaicSkillsDir -Recurse -Force
}

if (-not (Test-Path $MosaicSkillsDir)) {
    Write-Host "[mosaic-skills] Canonical skills dir missing: $MosaicSkillsDir" -ForegroundColor Red
    exit 1
}

if ($NoLink) {
    Write-Host "[mosaic-skills] Canonical sync completed (link update skipped)"
    exit 0
}

function Link-SkillIntoTarget {
    param([string]$SkillPath, [string]$TargetDir)

    $name = Split-Path $SkillPath -Leaf
    if ($name.StartsWith(".")) { return }

    $linkPath = Join-Path $TargetDir $name

    # Already a junction/symlink — recreate
    $existing = Get-Item $linkPath -Force -ErrorAction SilentlyContinue
    if ($existing -and ($existing.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) {
        Remove-Item $linkPath -Force
    }
    elseif ($existing) {
        Write-Host "[mosaic-skills] Preserve existing runtime-specific entry: $linkPath"
        return
    }

    # Try junction first, fall back to copy
    try {
        New-Item -ItemType Junction -Path $linkPath -Target $SkillPath -ErrorAction Stop | Out-Null
    }
    catch {
        Write-Host "[mosaic-skills] Junction failed for $name, falling back to copy"
        Copy-Item $SkillPath $linkPath -Recurse -Force
    }
}

$linkTargets = @(
    (Join-Path $env:USERPROFILE ".claude\skills"),
    (Join-Path $env:USERPROFILE ".codex\skills"),
    (Join-Path $env:USERPROFILE ".config\opencode\skills")
)

foreach ($target in $linkTargets) {
    if (-not (Test-Path $target)) { New-Item -ItemType Directory -Path $target -Force | Out-Null }

    # Link canonical skills
    Get-ChildItem $MosaicSkillsDir -Directory | ForEach-Object {
        Link-SkillIntoTarget $_.FullName $target
    }

    # Link local skills
    if (Test-Path $MosaicLocalSkillsDir) {
        Get-ChildItem $MosaicLocalSkillsDir -Directory | ForEach-Object {
            Link-SkillIntoTarget $_.FullName $target
        }
    }

    Write-Host "[mosaic-skills] Linked skills into: $target"
}

Write-Host "[mosaic-skills] Complete"
