# SOPS/Encryption Handler Engine
# Manages SOPS-encrypted configuration file detection, decryption, and validation

use std log

# Check if file is SOPS encrypted
export def check-if-sops-encrypted [file_path: string] {
    if not ($file_path | path exists) {
        return false
    }

    let file_content = (open $file_path --raw)

    # Check for SOPS markers
    if ($file_content | str contains "sops:") and ($file_content | str contains "ENC[") {
        return true
    }

    false
}

# Decrypt SOPS file
export def decrypt-sops-file [file_path: string] {
    # Find SOPS config
    let sops_config = find-sops-config-path

    # Decrypt using SOPS binary
    let result = if ($sops_config | is-not-empty) {
        ^sops --decrypt --config $sops_config $file_path | complete
    } else {
        ^sops --decrypt $file_path | complete
    }

    if $result.exit_code != 0 {
        return ""
    }

    $result.stdout
}

# Find SOPS configuration file
export def find-sops-config-path [] {
    # Check common locations
    let locations = [
        ".sops.yaml"
        ".sops.yml"
        ($env.PWD | path join ".sops.yaml")
        ($env.HOME | path join ".config" | path join "provisioning" | path join "sops.yaml")
    ]

    for loc in $locations {
        if ($loc | path exists) {
            return $loc
        }
    }

    ""
}

# Handle encrypted configuration file - wraps decryption logic
export def handle-encrypted-file [
    file_path: string
    config: record
] {
    if (check-if-sops-encrypted $file_path) {
        let decrypted = (decrypt-sops-file $file_path)
        if ($decrypted | is-not-empty) {
            # Determine file format from extension
            let ext = ($file_path | path parse | get extension)
            match $ext {
                "yaml" | "yml" => ($decrypted | from yaml)
                "toml" => ($decrypted | from toml)
                "json" => ($decrypted | from json)
                _ => ($decrypted | from yaml)
            }
        } else {
            {}
        }
    } else {
        # File is not encrypted, return empty to indicate no handling needed
        {}
    }
}
