# Workspace:Infrastructure Notation Parser
# Handles parsing and validation of unified workspace:infra notation

use ../user/config.nu *
use ../utils/config.nu *

# Parse workspace:infra notation
# Supports both "workspace" and "workspace:infra" formats
export def parse-workspace-infra-notation [spec: string] {
    if ($spec | str contains ":") {
        let parts = ($spec | split row ":")
        let workspace_part = ($parts | get 0)
        let infra_part = if ($parts | length) > 2 {
            ($parts | skip 1 | str join ":")
        } else {
            ($parts | get 1?)
        }
        {
            workspace: $workspace_part
            infra: ($infra_part | default "")
        }
    } else {
        {
            workspace: $spec
            infra: null
        }
    }
}

# Validate workspace exists
def workspace-exists? [workspace_name: string] {
    let config = (load-user-config)
    let workspace = ($config.workspaces | where name == $workspace_name | first)
    ($workspace | is-not-empty)
}

# Validate infrastructure exists in workspace
def infra-exists? [workspace_name: string, infra_name: string] {
    let config = (load-user-config)
    let workspace = ($config.workspaces | where name == $workspace_name | first)

    if ($workspace | is-empty) {
        return false
    }

    let workspace_path = ($workspace.path)
    let infra_path = ([$workspace_path "infra" $infra_name] | path join)
    let settings_file = ([$infra_path "settings.ncl"] | path join)

    ($settings_file | path exists)
}

# Validate workspace:infra specification
# Returns result record with validation status
export def validate-workspace-infra-spec [spec: string] {
    let parsed = (parse-workspace-infra-notation $spec)

    # Check workspace exists
    if not (workspace-exists? $parsed.workspace) {
        return {
            valid: false
            workspace: $parsed.workspace
            infra: $parsed.infra
            error: $"Workspace '($parsed.workspace)' not found"
        }
    }

    # Check infrastructure if specified
    if ($parsed.infra | is-not-empty) {
        if not (infra-exists? $parsed.workspace $parsed.infra) {
            return {
                valid: false
                workspace: $parsed.workspace
                infra: $parsed.infra
                error: $"Infrastructure '($parsed.infra)' not found in workspace '($parsed.workspace)'"
            }
        }
    }

    {
        valid: true
        workspace: $parsed.workspace
        infra: $parsed.infra
        error: null
    }
}

# Get workspace path from registry
export def get-workspace-path [workspace_name: string] {
    let config = (load-user-config)
    let workspace = ($config.workspaces | where name == $workspace_name | first)

    if ($workspace | is-empty) {
        return ""
    }

    $workspace.path
}

# List registered workspaces
export def list-workspaces [] {
    let config = (load-user-config)
    $config.workspaces
}
