#!/usr/bin/env nu
# Remove tenant registration stubs from a workspace repo.
# Usage: nu provisioning/unregister.nu --workspace <path> [--workspace-name secrets-base]
# Env: DEV_ROOT, PROVISIONING, LIAN_BUILD_ROOT
#
# Removes:
#   <workspace>/appserv/<ws-name>/<tenant>.ncl
#   <workspace>/builds/<tenant>.ncl
#
# Verifies the # source: annotation matches this project before removing.
# NEVER touches project.ncl, workspace overrides, or mode schemas.

def extract-source-path [path: string]: nothing -> string {
    if not ($path | path exists) { return "" }
    let matches = (open $path | lines | where { |l| $l | str starts-with "# source:" })
    if ($matches | is-empty) { return "" }
    ($matches | first | str replace "# source:" "" | split row " @ " | first | str trim)
}

def safe-remove [path: string, project_root: string, label: string]: nothing -> nothing {
    if not ($path | path exists) {
        print $"[unregister] ($label): not found — already removed or never registered"
        return
    }
    let source = (extract-source-path $path)
    if ($source | is-not-empty) and $source != $project_root {
        error make { msg: $"[unregister] ABORT: ($label) source annotation is ($source), expected ($project_root) — refusing to remove" }
    }
    rm $path
    print $"[unregister] removed ($path)"
}

def main [
    --workspace: string = ""
    --workspace-name: string = "secrets-base"
]: nothing -> nothing {
    if ($workspace | is-empty) {
        error make { msg: "Usage: nu provisioning/unregister.nu --workspace <secrets-base-infra-path>" }
    }
    if not ($workspace | path exists) {
        error make { msg: $"workspace path not found: ($workspace)" }
    }

    let dev_root     = ($env.DEV_ROOT? | default "/Users/Akasha/Development")
    let prov         = ($env.PROVISIONING? | default $"($dev_root)/project-provisioning/provisioning")
    let lb_root      = ($env.LIAN_BUILD_ROOT? | default $"($dev_root)/lian-build")
    let project_root = ($env.FILE_PWD | path dirname)

    let p = (
        ^nickel export
            --import-path $prov
            --import-path $lb_root
            $"($project_root)/provisioning/project.ncl"
            --format json
        | from json
    )

    let tenant = ($p.name | str replace -a "-" "_")

    let appserv_path = $"($workspace)/appserv/($workspace_name)/($p.name).ncl"
    let builds_path  = $"($workspace)/builds/($tenant).ncl"

    safe-remove $appserv_path $project_root "appserv"
    safe-remove $builds_path  $project_root "builds"

    print $"[unregister] done — tenant: ($p.name), workspace: ($workspace_name)"
}
