# Workspace management helper functions
# NUSHELL 0.109 COMPLIANT - Using each (Rule 8), no mutable variables (Rule 3)

# Get the currently active workspace
export def get-active-workspace [] {
    let user_config_dir = ([$env.HOME "Library" "Application Support" "provisioning"] | path join)

    if not ($user_config_dir | path exists) {
        return null
    }

    # Load central user config
    let user_config_path = ($user_config_dir | path join "user_config.yaml")

    if not ($user_config_path | path exists) {
        return null
    }

    let user_config = (open $user_config_path)

    # Check if active workspace is set
    if ($user_config.active_workspace == null) {
        null
    } else {
        # Find workspace in list
        let workspace_name = $user_config.active_workspace
        let workspace = ($user_config.workspaces | where name == $workspace_name | first)

        if ($workspace | is-empty) {
            null
        } else {
            {
                name: $workspace.name
                path: $workspace.path
            }
        }
    }
}

# Update workspace last used timestamp (internal)
export def update-workspace-last-used [workspace_name: string] {
    let user_config_dir = ([$env.HOME "Library" "Application Support" "provisioning"] | path join)
    let user_config_path = ($user_config_dir | path join "user_config.yaml")

    if not ($user_config_path | path exists) {
        return
    }

    let user_config = (open $user_config_path)

    # Update last_used timestamp for workspace
    let updated_config = (
        $user_config | upsert workspaces {|ws|
            $ws | each {|w|
                if $w.name == $workspace_name {
                    $w | upsert last_used (date now | format date '%Y-%m-%dT%H:%M:%SZ')
                } else {
                    $w
                }
            }
        }
    )

    $updated_config | to yaml | save --force $user_config_path
}

# Get project root directory
export def get-project-root [] {
    let markers = [".provisioning.toml", "provisioning.toml", ".git", "provisioning"]

    mut current = ($env.PWD | path expand)

    while $current != "/" {
        let found = ($markers
            | any {|marker|
                (($current | path join $marker) | path exists)
            }
        )

        if $found {
            return $current
        }

        $current = ($current | path dirname)
    }

    $env.PWD
}
