use std
# config/accessor star-import was dead — dropped (ADR-025 Phase 3 Layer 2).
use lib_provisioning/utils/error.nu [throw-error]
use lib_provisioning/utils/interface.nu [_print]
use lib_provisioning/plugins/kms.nu [plugin-kms-encrypt plugin-kms-decrypt plugin-kms-info]

def find_file [
    start_path: string
    match_path: string
    only_first: bool
] {
    mut found_path = ""
    mut search_path = $start_path
    let home_root = ($env.HOME | path dirname)
    while $found_path == "" and  $search_path != "/" and $search_path != $home_root {
        if $search_path == "" { break }
        let res = if $only_first {
            (^find $search_path -type f -name $match_path -print -quit | complete)
        } else {
            (^find $search_path -type f -name $match_path err> (if $nu.os-info.name == "windows" { "NUL" } else { "/dev/null" }) | complete)
        }
    if $res.exit_code == 0 { $found_path = ($res.stdout | str trim )  }
        $search_path = ($search_path | path dirname)
    }
    $found_path
}

export def run_cmd_kms [
    task: string
    cmd: string
    source_path: string
    error_exit: bool
] {
    # Try plugin-based KMS first (10x faster)
    let plugin_info = (plugin-kms-info)

    if $plugin_info.plugin_available and $plugin_info.plugin_enabled {
        let file_content = (do -i { open -r $source_path } | default "")
        if ($file_content | is-empty) {
            if $error_exit {
                (throw-error $"🛑 KMS error" $"(_ansi red)Cannot read file: ($source_path)(_ansi reset)"
                    "run_cmd_kms" --span (metadata $source_path).span)
            }
            return ""
        }

        let result = (do -i {
            if $cmd == "encrypt" {
                (plugin-kms-encrypt $file_content --backend $plugin_info.default_backend)
            } else if $cmd == "decrypt" {
                (plugin-kms-decrypt $file_content --backend $plugin_info.default_backend)
            } else {
                ""
            }
        })

        if $result != null {
            if (($result | describe) | str starts-with "record") and "ciphertext" in $result {
                return $result.ciphertext
            } else if (($result | describe) | str starts-with "string") {
                return $result
            }
        } else {
            # Plugin failed, fall through to HTTP/CLI fallback
            if (get-debug-mode) {
                _print $"⚠️  Plugin KMS ($cmd) failed, using fallback"
            }
        }
    }

    # Fallback to HTTP/CLI implementation
    let kms_config = get_kms_config
    if ($kms_config | is-empty) {
        if $error_exit {
            (throw-error $"🛑 KMS configuration error" $"(_ansi red)No KMS configuration found(_ansi reset)"
                "run_cmd_kms" --span (metadata $task).span)
        } else {
            _print $"🛑 KMS configuration error (_ansi red)No KMS configuration found(_ansi reset)"
            return ""
        }
    }

    let res = (run_kms_curl $cmd $source_path $kms_config | complete)

    if $res.exit_code != 0 {
        if $error_exit {
            (throw-error $"🛑 KMS error" $"(_ansi red)($source_path)(_ansi reset) ($res.stdout)"
                $"on_kms ($task)" --span (metadata $res).span)
        } else {
            _print $"🛑 KMS error (_ansi red)($source_path)(_ansi reset) ($res.exit_code)"
            return ""
        }
    }
    return $res.stdout
}

def run_kms_curl [
    operation: string
    file_path: string
    config: record
] {
    # Validate file path exists to prevent injection
    if not ($file_path | path exists) {
        error make {msg: $"File does not exist: ($file_path)"}
    }

    mut curl_args = []

    # SSL verification
    if not $config.verify_ssl {
        $curl_args = ($curl_args | append "-k")
    }

    # Timeout
    $curl_args = ($curl_args | append "--connect-timeout")
    $curl_args = ($curl_args | append ($config.timeout | into string))

    # Authentication
    match $config.auth_method {
        "certificate" => {
            if ($config.client_cert | is-not-empty) and ($config.client_key | is-not-empty) {
                $curl_args = ($curl_args | append "--cert")
                $curl_args = ($curl_args | append $config.client_cert)
                $curl_args = ($curl_args | append "--key")
                $curl_args = ($curl_args | append $config.client_key)
            }
            if ($config.ca_cert | is-not-empty) {
                $curl_args = ($curl_args | append "--cacert")
                $curl_args = ($curl_args | append $config.ca_cert)
            }
        },
        "token" => {
            if ($config.api_token | is-not-empty) {
                $curl_args = ($curl_args | append "-H")
                $curl_args = ($curl_args | append $"Authorization: Bearer ($config.api_token)")
            }
        },
        "basic" => {
            if ($config.username | is-not-empty) and ($config.password | is-not-empty) {
                $curl_args = ($curl_args | append "--user")
                $curl_args = ($curl_args | append $"($config.username):($config.password)")
            }
        }
    }

    # Operation specific parameters
    match $operation {
        "encrypt" => {
            $curl_args = ($curl_args | append "-X")
            $curl_args = ($curl_args | append "POST")
            $curl_args = ($curl_args | append "-H")
            $curl_args = ($curl_args | append "Content-Type: application/octet-stream")
            $curl_args = ($curl_args | append "--data-binary")
            $curl_args = ($curl_args | append $"@($file_path)")
            $curl_args = ($curl_args | append $"($config.server_url)/encrypt")
        },
        "decrypt" => {
            $curl_args = ($curl_args | append "-X")
            $curl_args = ($curl_args | append "POST")
            $curl_args = ($curl_args | append "-H")
            $curl_args = ($curl_args | append "Content-Type: application/octet-stream")
            $curl_args = ($curl_args | append "--data-binary")
            $curl_args = ($curl_args | append $"@($file_path)")
            $curl_args = ($curl_args | append $"($config.server_url)/decrypt")
        }
    }

    ^curl ...$curl_args
}

export def on_kms [
    task: string
    source_path: string
    output_path?: string
    ...args
    --check (-c)
    --error_exit
    --quiet
] {
    match $task {
        "encrypt" | "encode" | "e" => {
            if not ( $source_path | path exists ) {
                if not $quiet { _print $"🛑 No file ($source_path) found to encrypt with KMS " }
                return ""
            }
            if (is_kms_file $source_path) {
                if not $quiet { _print $"🛑 File ($source_path) already encrypted with KMS " }
                return (open -r $source_path)
            }
            let result = (run_cmd_kms "encrypt" "encrypt" $source_path  $error_exit)
            if ($output_path | is-not-empty) {
                $result | save -f $output_path
                if not $quiet { _print $"Result saved in ($output_path) " }
            }
            return $result
        },
        "decrypt" | "decode" | "d" => {
            if not ( $source_path | path exists ) {
                if not $quiet { _print $"🛑 No file ($source_path) found to decrypt with KMS " }
                return ""
            }
            if not (is_kms_file $source_path) {
                if not $quiet { _print $"🛑 File ($source_path) is not encrypted with KMS " }
                return (open -r $source_path)
            }
            let result = (run_cmd_kms "decrypt" "decrypt" $source_path  $error_exit)
            if ($output_path | is-not-empty) {
                $result | save -f $output_path
                if not $quiet { _print $"Result saved in ($output_path) " }
            }
            return $result
        },
        "is_kms" | "i" => {
            return (is_kms_file $source_path)
        },
        _ => {
            (throw-error $"🛑 Option " $"(_ansi red)($task)(_ansi reset) undefined")
            return ""
        }
    }
}

export def is_kms_file [
    target: string
] {
    if not ($target | path exists) {
        (throw-error $"🛑 File (_ansi green_italic)($target)(_ansi reset)"
           $"(_ansi red_bold)Not found(_ansi reset)"
           $"is_kms_file ($target)"
            --span (metadata $target).span
        )
    }
    let file_content = (open $target --raw)
    # Check for KMS-specific markers in the encrypted file
    if ($file_content | find "-----BEGIN KMS ENCRYPTED DATA-----" | length) > 0 { return true }
    if ($file_content | find "kms:" | length) > 0 { return true }
    return false
}

export def decode_kms_file [
    source: string
    target: string
    quiet: bool
] {
  if $quiet {
    on_kms "decrypt" $source --quiet
  } else {
    on_kms "decrypt" $source
  }  | save --force $target
}

def get_kms_config [] {
    let server_url = (get-kms-server)
    if ($server_url | is-empty) {
        return {}
    }

    {
        server_url: $server_url,
        auth_method: (get-kms-auth-method),
        client_cert: (get-kms-client-cert),
        client_key: (get-kms-client-key),
        ca_cert: (get-kms-ca-cert),
        api_token: (get-kms-api-token),
        username: (get-kms-username),
        password: (get-kms-password),
        timeout: (get-kms-timeout | into int),
        verify_ssl: (get-kms-verify-ssl | into bool)
    }
}


export def get_def_kms_config [
    current_path: string
] {
    let use_kms = (get-provisioning-use-kms)
    if ($use_kms | is-empty) { return ""}
    let start_path = if ($current_path | path exists) {
        $current_path
    } else {
        $"((get-workspace-path))/($current_path)"
    }
    let kms_file = "kms.yaml"
    mut provisioning_kms = (find_file $start_path $kms_file true )
    if $provisioning_kms == "" and ($env.HOME | path join ".config"| path join "provisioning" | path join $kms_file | path exists ) {
        $provisioning_kms = ($env.HOME | path join ".config"| path join "provisioning" | path join $kms_file )
    }
    if $provisioning_kms == "" and ($env.HOME | path join ".provisioning"| path join $kms_file | path exists ) {
       $provisioning_kms = ($env.HOME | path join ".provisioning"| path join $kms_file )
    }
    if $provisioning_kms == "" {
        _print $"❗Error no (_ansi red_bold)($kms_file)(_ansi reset) file for KMS operations found "
        exit 1
    }
    ($provisioning_kms | default "")
}
