# Module: Path Resolution Utilities
# Purpose: Provides helpers for resolving provisioning project root and constructing absolute paths
# Used by: TypeDialog integration, setup wizard, auth forms

# Resolve provisioning project root with multiple fallback strategies
# Returns: The root directory that CONTAINS the provisioning folder
export def resolve-provisioning-root [] {
    if "PROVISIONING_ROOT" in $env {
        return $env.PROVISIONING_ROOT
    }

    if "PROVISIONING" in $env {
        # PROVISIONING env var points to the provisioning folder itself
        # We need its parent directory
        let provisioning_dir = $env.PROVISIONING
        let parent = ($provisioning_dir | path dirname)

        # Verify the parent contains the provisioning folder
        if ($parent | path join "provisioning" | path exists) {
            return $parent
        } else {
            # PROVISIONING is already the project root
            return $provisioning_dir
        }
    }

    # Find project root by walking up from current directory
    # We're looking for the directory that CONTAINS the provisioning folder
    mut search_dir = (pwd)
    mut found_root = ""

    # Try 10 levels up maximum to find project root
    for i in (0..9) {
        let provisioning_path = ($search_dir | path join "provisioning")
        if ($provisioning_path | path exists) and (($provisioning_path | path type) == "dir") {
            # Found the root - it's the parent of the provisioning dir
            $found_root = $search_dir
            break
        }

        let parent = ($search_dir | path dirname)
        if $parent == $search_dir {
            break  # Reached filesystem root
        }

        $search_dir = $parent
    }

    if ($found_root | is-empty) {
        # Last resort: return current directory
        pwd
    } else {
        $found_root
    }
}

# Get TypeDialog form path with absolute resolution
export def get-typedialog-form-path [form_name: string] {
    let provisioning_root = (resolve-provisioning-root)
    $provisioning_root | path join "provisioning" ".typedialog" "core" "forms" $form_name
}
