#!/usr/bin/env nu
# Configurable formatters for version status display

# Status icon mapping (configurable)
export def status-icons []: nothing -> record {
    {
        fixed: "🔒"
        not_installed: "❌"
        update_available: "⬆️"
        behind_config: "⚠️"
        ahead_config: "🔄"
        up_to_date: "✅"
        unknown: "❓"
    }
}

# Format status with configurable icons
export def format-status [
    status: string
    --icons: record = {}
]: nothing -> string {
    let icon_map = if ($icons | is-empty) { (status-icons) } else { $icons }
    let icon = ($icon_map | get -o $status | default $icon_map.unknown)

    let text = match $status {
        "fixed" => "Fixed"
        "not_installed" => "Not installed"
        "update_available" => "Update available"
        "behind_config" => "Behind config"
        "ahead_config" => "Ahead of config"
        "up_to_date" => "Up to date"
        _ => "Unknown"
    }

    $"($icon) ($text)"
}

# Format version results as table
export def format-results [
    results: list
    --group-by: string = "type"
    --show-fields: list = ["id", "installed", "configured", "latest", "status"]
    --icons: record = {}
]: nothing -> nothing {
    if ($results | is-empty) {
        print "No components found"
        return
    }

    # Group results if requested
    if ($group_by | is-not-empty) {
        let grouped = ($results | group-by { |r| $r | get -o $group_by | default "unknown" })

        for group in ($grouped | transpose key value) {
            print $"\n### ($group.key | str capitalize)"

            let formatted = ($group.value | each { |item|
                mut row = {}
                for field in $show_fields {
                    if $field == "status" {
                        $row = ($row | insert $field (format-status $item.status --icons=$icons))
                    } else {
                        $row = ($row | insert $field ($item | get -o $field | default ""))
                    }
                }
                $row
            })

            print ($formatted | table)
        }
    } else {
        # Direct table output
        let formatted = ($results | each { |item|
            mut row = {}
            for field in $show_fields {
                if $field == "status" {
                    $row = ($row | insert $field (format-status $item.status --icons=$icons))
                } else {
                    $row = ($row | insert $field ($item | get -o $field | default ""))
                }
            }
            $row
        })

        print ($formatted | table)
    }

    # Summary
    print "\n📊 Summary:"
    let by_status = ($results | group-by status)
    for status in ($by_status | transpose key value) {
        print $"  (format-status $status.key --icons=$icons): ($status.value | length)"
    }
}