# Extension Management CLI Commands

use loader_oci.nu load-extension
use cache.nu *
use discovery.nu *
use versions.nu *
use ../utils/logging.nu *

# Load extension from any source
export def "ext load" [
    extension_name: string          # Extension name
    --type: string = "taskserv"     # Extension type (provider, taskserv, cluster)
    --version: string = "latest"    # Version constraint
    --source: string = "auto"       # Source type (auto, oci, gitea, local)
    --force (-f)                    # Force reload
] {
    print $"Loading extension: ($extension_name)"

    let result = (load-extension $type $extension_name $version --source-type $source --force=$force)

    if $result.success {
        print $"✅ Loaded ($extension_name):($result.version?) from ($result.source)"
    } else {
        print $"❌ Failed to load ($extension_name): ($result.error?)"
        exit 1
    }
}

# Search for extensions
export def "ext search" [
    query: string                   # Search query
    --source: string = "all"        # Source to search (all, oci, gitea, local)
] {
    print $"Searching for: ($query)"

    let results = (search-extensions $query --source $source)

    if ($results | is-empty) {
        print "   (no extensions found)"
        return
    }

    print ""
    $results | select name type version source | sort-by type name
}

# List available extensions
export def "ext list" [
    --type: string = ""             # Filter by extension type
    --source: string = "all"        # Source to list (all, oci, gitea, local)
    --format: string = "table"      # Output format (table, json, yaml)
] {
    list-extensions --extension-type $type --source $source --format $format
}

# Show extension info
export def "ext info" [
    extension_name: string          # Extension name
    --version: string = "latest"    # Extension version
    --source: string = "auto"       # Source type
] {
    print $"Extension: ($extension_name)"

    # Discover to find extension
    let all_extensions = (discover-all-extensions)
    let matches = ($all_extensions | where name == $extension_name)

    if ($matches | is-empty) {
        print "   ❌ Extension not found"
        return
    }

    for ext in $matches {
        print ""
        print $"  Source: ($ext.source)"
        print $"  Type: ($ext.type)"
        print $"  Version: ($ext.version)"

        if ($ext.description? | is-not-empty) {
            print $"  Description: ($ext.description)"
        }

        if $ext.source == "oci" {
            print $"  Registry: ($ext.registry)"
            print $"  Namespace: ($ext.namespace)"
        }

        if $ext.source == "local" {
            print $"  Path: ($ext.path)"
        }
    }
}

# List extension versions
export def "ext versions" [
    extension_name: string          # Extension name
    --source: string = "all"        # Source to check
] {
    print $"Versions of ($extension_name):"

    let versions = (get-extension-versions $extension_name --source $source)

    if ($versions | is-empty) {
        print "   (no versions found)"
        return
    }

    $versions | select version source | sort-by source version
}

# Cache management commands
export def "ext cache list" [
    --type: string = ""             # Filter by extension type
] {
    list-cached --extension-type $type
}

export def "ext cache clear" [
    --type: string = ""             # Extension type to clear
    --name: string = ""             # Extension name to clear
    --all                           # Clear all cache
] {
    if $all {
        clear-cache
        print "✅ Cleared all extension cache"
    } else if ($type | is-not-empty) and ($name | is-not-empty) {
        clear-cache --extension-type $type --extension-name $name
        print $"✅ Cleared cache for ($name)"
    } else if ($type | is-not-empty) {
        clear-cache --extension-type $type
        print $"✅ Cleared cache for all ($type)"
    } else {
        print "❌ Specify --all, or --type and --name"
        exit 1
    }
}

export def "ext cache stats" [] {
    let stats = (get-cache-stats)

    print "📊 Extension Cache Statistics"
    print ""
    print $"   Total extensions: ($stats.total_extensions)"
    print $"   Total size: ($stats.total_size_bytes) bytes"
    print $"   Cache directory: ($stats.cache_dir)"
    print $"   Last updated: ($stats.last_updated)"
    print ""
    print "   By type:"

    for type_stat in $stats.by_type {
        print $"     • ($type_stat.type): ($type_stat.count)"
    }

    print ""
    print "   By source:"

    for source_stat in $stats.by_source {
        print $"     • ($source_stat.source): ($source_stat.count)"
    }
}

export def "ext cache prune" [
    --days: int = 30                # Remove entries older than days
] {
    print $"Pruning cache entries older than ($days) days..."

    let result = (prune-cache $days)

    print $"✅ Removed ($result.removed_count) extensions"

    if ($result.removed_extensions | length) > 0 {
        print ""
        print "   Removed:"
        for ext in $result.removed_extensions {
            print $"     • ($ext.name) ($ext.version) - ($ext.type)"
        }
    }
}

# Pull extension to cache without loading
export def "ext pull" [
    extension_name: string          # Extension name
    --type: string = "taskserv"     # Extension type
    --version: string = "latest"    # Version to pull
    --source: string = "auto"       # Source type
] {
    print $"Pulling ($extension_name):($version) to cache..."

    let result = (load-extension $type $extension_name $version --source-type $source)

    if $result.success {
        print $"✅ Pulled ($extension_name):($result.version?) to cache"
    } else {
        print $"❌ Failed to pull: ($result.error?)"
        exit 1
    }
}

# Publish extension to OCI registry
export def "ext publish" [
    extension_path: string          # Path to extension
    --version: string               # Version to publish
    --registry: string = ""         # OCI registry
    --namespace: string = ""        # Registry namespace
    --force (-f)                    # Overwrite existing
] {
    # Delegate to publish_extension.nu tool
    let tool_path = ($env.FILE_PWD | path dirname | path dirname | path dirname | path dirname | path join "tools" "publish_extension.nu")

    let args = [
        $extension_path
        --version $version
    ]

    let args_with_registry = if ($registry | is-not-empty) {
        $args | append [--registry $registry]
    } else {
        $args
    }

    let args_with_namespace = if ($namespace | is-not-empty) {
        $args_with_registry | append [--namespace $namespace]
    } else {
        $args_with_registry
    }

    let final_args = if $force {
        $args_with_namespace | append [--force]
    } else {
        $args_with_namespace
    }

    nu $tool_path ...$final_args
}

# Discover extensions from all sources
export def "ext discover" [
    --type: string = ""             # Filter by type
    --refresh                       # Force refresh from sources
] {
    print "🔍 Discovering extensions..."

    let extensions = (discover-all-extensions $type)

    if ($extensions | is-empty) {
        print "   (no extensions found)"
        return
    }

    print ""
    print $"Found ($extensions | length) extensions:"
    print ""

    $extensions | select name type version source | sort-by type source name
}

# Test OCI connection
export def "ext test-oci" [] {
    use ../oci/client.nu test-oci-connection

    print "Testing OCI registry connection..."
    print ""

    let result = (test-oci-connection)

    print $"   Registry reachable: ($result.registry_reachable)"
    print $"   Authentication valid: ($result.authentication_valid)"
    print $"   Catalog accessible: ($result.catalog_accessible)"

    if ($result.errors | is-not-empty) {
        print ""
        print "   Errors:"
        for error in $result.errors {
            print $"     • ($error)"
        }
    }
}
