# SOPS Command Handler
# Domain: SOPS encrypted file editing

# REMOVED: use ../../../lib_provisioning * - causes circular import

# SOPS edit command handler - Edit SOPS encrypted files (sed is alias)
export def handle_sops_edit [task: string, ops: string, flags: record] {
    let pos = if $task == "sed" { 0 } else { 1 }
    let ops_parts = ($ops | split row " ")
    let target_file = if ($ops_parts | length) > $pos { $ops_parts | get $pos } else { "" }

    if ($target_file | is-empty) {
        throw-error $"🛑 No file found" $"for (_ansi yellow_bold)sops(_ansi reset) edit"
        exit -1
    }

    let target_full_path = if not ($target_file | path exists) {
        let infra_path = (get_infra $flags.infra)
        let candidate = ($infra_path | path join $target_file)
        if ($candidate | path exists) {
            $candidate
        } else {
            throw-error $"🛑 No file (_ansi green_italic)($target_file)(_ansi reset) found" $"for (_ansi yellow_bold)sops(_ansi reset) edit"
            exit -1
        }
    } else {
        $target_file
    }

    # Setup SOPS environment if needed
    if ($env.PROVISIONING_SOPS? | is-empty) {
        let curr_settings = (find_get_settings --infra $flags.infra --settings $flags.settings $flags.include_notuse)
        rm -rf $curr_settings.wk_path
        $env.CURRENT_INFRA_PATH = ($curr_settings.infra_path | path join $curr_settings.infra)
        use ../../../sops_env.nu
    }

    if $task == "sed" {
        on_sops "sed" $target_full_path
    } else {
        on_sops $task $target_full_path ($ops_parts | skip 1)
    }
}
