# Help System with Fluent i18n Integration
# Loads help strings from Fluent catalogs based on LANG environment variable
# Falls back to English (en-US) if translation missing

use ../lib_provisioning/config/accessor.nu *

# Format alias: brackets in gray, inner text in category color
def format-alias [alias: string, color: string] {
    if ($alias | is-empty) {
        ""
    } else if ($alias | str starts-with "[") and ($alias | str ends-with "]") {
        # Extract content between brackets (exclusive end range)
        let inner = ($alias | str substring 1..<(-1))
        (ansi d) + "[" + (ansi rst) + $color + $inner + (ansi rst) + (ansi d) + "]" + (ansi rst)
    } else {
        (ansi d) + $alias + (ansi rst)
    }
}

# Format categories with tab-separated columns and colors
def format-categories [rows: list<list<string>>] {
    let header = "  Category\t\tAlias\t Description"
    let separator = "  ════════════════════════════════════════════════════════════════════"

    let formatted_rows = (
        $rows | each { |row|
            let emoji = $row.0
            let name = $row.1
            let alias = $row.2
            let desc = $row.3

            # Assign color based on category name
            let color = (match $name {
                "infrastructure" => (ansi cyan)
                "orchestration" => (ansi magenta)
                "development" => (ansi green)
                "workspace" => (ansi green)
                "setup" => (ansi magenta)
                "platform" => (ansi red)
                "authentication" => (ansi yellow)
                "plugins" => (ansi cyan)
                "utilities" => (ansi green)
                "tools" => (ansi yellow)
                "vm" => (ansi white)
                "diagnostics" => (ansi magenta)
                "concepts" => (ansi yellow)
                "guides" => (ansi blue)
                "integrations" => (ansi cyan)
                _ => ""
            })

            # Calculate tabs and format alias
            let name_len = ($name | str length)
            let alias_len = ($alias | str length)
            let name_tabs = match true {
                _ if $name_len <= 11 => "\t\t"
                _ => "\t"
            }

            # Format alias with brackets in gray and inner text in category color
            let alias_formatted = (format-alias $alias $color)
            let alias_tabs = match true {
                _ if $alias_len == 8 => ""
                _ if $name_len <= 3 => "\t\t"
                _ => "\t"
            }

            # Format: emoji + colored_name + tabs + colored_alias + tabs + description
            $"  ($emoji)($color)($name)((ansi rst))($name_tabs)($alias_formatted)($alias_tabs) ($desc)"
        }
    )

    ([$header, $separator] | append $formatted_rows | str join "\n")
}

# Get active locale from LANG environment variable
export def get-active-locale [] {
    let lang_env = ($env.LANG? | default "en_US")

    # Parse LANG format (e.g., "es_ES.UTF-8" → "es-ES")
    # Note: str index-of returns -1 if not found, not null
    let dot_idx = ($lang_env | str index-of ".")
    let lang_part = (
        if $dot_idx >= 0 {
            $lang_env | str substring 0..<$dot_idx
        } else {
            $lang_env
        }
    )

    let locale = ($lang_part | str replace "_" "-")
    $locale
}

# Parse simple Fluent format and return record of strings
export def parse-fluent [content: string] {
    let lines = ($content | lines)

    $lines | reduce -f {} { |line, strings|
        # Skip comments and empty lines
        if ($line | str starts-with "#") or ($line | str trim | is-empty) {
            $strings
        } else if ($line | str contains " = ") {
            # Parse "key = value" format
            let idx = ($line | str index-of " = ")
            if $idx != null {
                let key = ($line | str substring 0..$idx | str trim)
                let value = ($line | str substring ($idx + 3).. | str trim | str trim -c "\"")
                $strings | insert $key $value
            } else {
                $strings
            }
        } else {
            $strings
        }
    }
}

# Get a help string with fallback
export def get-help-string [key: string] {
    let locale = (get-active-locale)
    # Use environment variable PROVISIONING as base path
    let prov_path = ($env.PROVISIONING? | default "/usr/local/provisioning/provisioning")
    let base_path = $"($prov_path)/locales"

    # Try locale-specific file
    let locale_file = $"($base_path)/($locale)/help.ftl"
    let fallback_file = $"($base_path)/en-US/help.ftl"

    let content = (
        if ($locale_file | path exists) {
            open $locale_file
        } else {
            open $fallback_file
        }
    )

    let strings = (parse-fluent $content)
    $strings | get $key | default "[$key]"
}

# Main help dispatcher
export def provisioning-help [
    category?: string
] {
    if ($category == null) or ($category == "") {
        return (help-main)
    }

    let result = (match $category {
        "infrastructure" | "infra" => "infrastructure"
        "orchestration" | "orch" => "orchestration"
        "development" | "dev" => "development"
        "workspace" | "ws" => "workspace"
        "platform" | "plat" => "platform"
        "setup" | "st" => "setup"
        "authentication" | "auth" => "authentication"
        "mfa" => "mfa"
        "plugins" | "plugin" => "plugins"
        "utilities" | "utils" | "cache" => "utilities"
        "tools" => "tools"
        "vm" => "vm"
        "diagnostics" | "diag" | "status" | "health" => "diagnostics"
        "concepts" | "concept" => "concepts"
        "guides" | "guide" | "howto" => "guides"
        "integrations" | "integration" | "int" => "integrations"
        _ => "unknown"
    })

    if $result == "unknown" {
        print $"❌ (get-help-string 'help-error-unknown-category'): \"($category)\"\n"
        print "$(get-help-string 'help-error-available-categories'):"
        print "  infrastructure [infra]  - $(get-help-string 'help-main-infrastructure-desc')"
        print "  orchestration [orch]    - $(get-help-string 'help-main-orchestration-desc')"
        print "  development [dev]       - $(get-help-string 'help-main-development-desc')"
        print "  workspace [ws]          - $(get-help-string 'help-main-workspace-desc')"
        print "  setup [st]              - $(get-help-string 'help-main-setup-desc')"
        print "  platform [plat]         - $(get-help-string 'help-main-platform-desc')"
        print "  authentication [auth]   - $(get-help-string 'help-main-authentication-desc')"
        print "  mfa                     - $(get-help-string 'help-main-authentication-desc')"
        print "  plugins [plugin]        - $(get-help-string 'help-main-plugins-desc')"
        print "  utilities [utils]       - $(get-help-string 'help-main-utilities-desc')"
        print "  tools                   - $(get-help-string 'help-main-tools-desc')"
        print "  vm                      - $(get-help-string 'help-main-vm-desc')"
        print "  diagnostics [diag]      - $(get-help-string 'help-main-diagnostics-desc')"
        print "  concepts [concept]      - $(get-help-string 'help-main-concepts-desc')"
        print "  guides [guide]          - $(get-help-string 'help-main-guides-desc')"
        print "  integrations [int]      - $(get-help-string 'help-main-integrations-desc')\n"
        print "$(get-help-string 'help-error-use-help')"
        exit 1
    }

    match $result {
        "infrastructure" => (help-infrastructure)
        "orchestration" => (help-orchestration)
        "development" => (help-development)
        "workspace" => (help-workspace)
        "platform" => (help-platform)
        "setup" => (help-setup)
        "authentication" => (help-authentication)
        "mfa" => (help-mfa)
        "plugins" => (help-plugins)
        "utilities" => (help-utilities)
        "tools" => (help-tools)
        "vm" => (help-vm)
        "diagnostics" => (help-diagnostics)
        "concepts" => (help-concepts)
        "guides" => (help-guides)
        "integrations" => (help-integrations)
        _ => (help-main)
    }
}

# Main help overview with categories
def help-main [] {
    let show_header = not ($env.PROVISIONING_NO_TITLES? | default false)
    let title = (get-help-string "help-main-title")
    let subtitle = (get-help-string "help-main-subtitle")

    let header = if $show_header {
        ("════════════════════════════════════════════════════════════════════════════\n" +
        $"  ($title) - ($subtitle)\n" +
        "════════════════════════════════════════════════════════════════════════════\n\n")
    } else {
        ""
    }

    let categories = (get-help-string "help-main-categories")
    let hint = (get-help-string "help-main-categories-hint")

    let categories_header = $"📚 ($categories) - ($hint)\n\n"

    let infra_desc = (get-help-string "help-main-infrastructure-desc")
    let orch_desc = (get-help-string "help-main-orchestration-desc")
    let dev_desc = (get-help-string "help-main-development-desc")
    let ws_desc = (get-help-string "help-main-workspace-desc")
    let plat_desc = (get-help-string "help-main-platform-desc")
    let setup_desc = (get-help-string "help-main-setup-desc")
    let auth_desc = (get-help-string "help-main-authentication-desc")
    let plugins_desc = (get-help-string "help-main-plugins-desc")
    let utils_desc = (get-help-string "help-main-utilities-desc")
    let tools_desc = (get-help-string "help-main-tools-desc")
    let vm_desc = (get-help-string "help-main-vm-desc")
    let diag_desc = (get-help-string "help-main-diagnostics-desc")
    let concepts_desc = (get-help-string "help-main-concepts-desc")
    let guides_desc = (get-help-string "help-main-guides-desc")
    let int_desc = (get-help-string "help-main-integrations-desc")

    let rows = [
        ["🏗️", "infrastructure", "[infra]", $infra_desc],
        ["⚡", "orchestration", "[orch]", $orch_desc],
        ["🧩", "development", "[dev]", $dev_desc],
        ["📁", "workspace", "[ws]", $ws_desc],
        ["⚙️", "setup", "[st]", $setup_desc],
        ["🖥️", "platform", "[plat]", $plat_desc],
        ["🔐", "authentication", "[auth]", $auth_desc],
        ["🔌", "plugins", "[plugin]", $plugins_desc],
        ["🛠️", "utilities", "[utils]", $utils_desc],
        ["🌉", "tools", "", $tools_desc],
        ["🔍", "vm", "", $vm_desc],
        ["📚", "diagnostics", "[diag]", $diag_desc],
        ["💡", "concepts", "", $concepts_desc],
        ["📖", "guides", "[guide]", $guides_desc],
        ["🌐", "integrations", "[int]", $int_desc],
    ]

    let categories_table = (format-categories $rows)

    print ($header + $categories_header + $categories_table)
}

# Infrastructure help
def help-infrastructure [] {
    let title = (get-help-string "help-infrastructure-title")
    print $"
╔════════════════════════════════════════════════════════════════╗
║ ($title) ║
╚════════════════════════════════════════════════════════════════╝
"

    let server = (get-help-string "help-infra-server")
    let server_create = (get-help-string "help-infra-server-create")
    let server_list = (get-help-string "help-infra-server-list")
    let server_status = (get-help-string "help-infra-server-status")
    let server_delete = (get-help-string "help-infra-server-delete")

    print $"🖥️  ($server)"
    print $"   ($server_create)"
    print $"   ($server_list)"
    print $"   ($server_status)"
    print $"   ($server_delete)\n"

    let taskserv = (get-help-string "help-infra-taskserv")
    let taskserv_create = (get-help-string "help-infra-taskserv-create")
    let taskserv_list = (get-help-string "help-infra-taskserv-list")
    let taskserv_logs = (get-help-string "help-infra-taskserv-logs")
    let taskserv_delete = (get-help-string "help-infra-taskserv-delete")

    print $"📦 ($taskserv)"
    print $"   ($taskserv_create)"
    print $"   ($taskserv_list)"
    print $"   ($taskserv_logs)"
    print $"   ($taskserv_delete)\n"

    let cluster = (get-help-string "help-infra-cluster")
    let cluster_create = (get-help-string "help-infra-cluster-create")
    let cluster_add = (get-help-string "help-infra-cluster-add-node")
    let cluster_remove = (get-help-string "help-infra-cluster-remove-node")
    let cluster_status = (get-help-string "help-infra-cluster-status")

    print $"🔗 ($cluster)"
    print $"   ($cluster_create)"
    print $"   ($cluster_add)"
    print $"   ($cluster_remove)"
    print $"   ($cluster_status)\n"

    let vm = (get-help-string "help-infra-vm")
    let vm_create = (get-help-string "help-infra-vm-create")
    let vm_start = (get-help-string "help-infra-vm-start")
    let vm_stop = (get-help-string "help-infra-vm-stop")
    let vm_reboot = (get-help-string "help-infra-vm-reboot")

    print $"💾 ($vm)"
    print $"   ($vm_create)"
    print $"   ($vm_start)"
    print $"   ($vm_stop)"
    print $"   ($vm_reboot)\n"

    let tip = (get-help-string "help-infra-tip")
    print $"💡 ($tip)\n"
}

# Orchestration help
def help-orchestration [] {
    let title = (get-help-string "help-orchestration-title")
    print $"
╔════════════════════════════════════════════════════════════════╗
║ ($title) ║
╚════════════════════════════════════════════════════════════════╝
"

    let control = (get-help-string "help-orch-control")
    let start = (get-help-string "help-orch-start")
    let stop = (get-help-string "help-orch-stop")
    let status = (get-help-string "help-orch-status")
    let health = (get-help-string "help-orch-health")
    let logs = (get-help-string "help-orch-logs")

    print $"🎯 ($control)"
    print $"   ($start)"
    print $"   ($stop)"
    print $"   ($status)"
    print $"   ($health)"
    print $"   ($logs)\n"

    let workflows = (get-help-string "help-orch-workflows")
    let workflow_list = (get-help-string "help-orch-workflow-list")
    let workflow_status = (get-help-string "help-orch-workflow-status")
    let workflow_monitor = (get-help-string "help-orch-workflow-monitor")
    let workflow_stats = (get-help-string "help-orch-workflow-stats")
    let workflow_cleanup = (get-help-string "help-orch-workflow-cleanup")

    print $"📋 ($workflows)"
    print $"   ($workflow_list)"
    print $"   ($workflow_status)"
    print $"   ($workflow_monitor)"
    print $"   ($workflow_stats)"
    print $"   ($workflow_cleanup)\n"

    let batch = (get-help-string "help-orch-batch")
    let batch_submit = (get-help-string "help-orch-batch-submit")
    let batch_list = (get-help-string "help-orch-batch-list")
    let batch_status = (get-help-string "help-orch-batch-status")
    let batch_monitor = (get-help-string "help-orch-batch-monitor")
    let batch_rollback = (get-help-string "help-orch-batch-rollback")
    let batch_cancel = (get-help-string "help-orch-batch-cancel")
    let batch_stats = (get-help-string "help-orch-batch-stats")

    print $"📦 ($batch)"
    print $"   ($batch_submit)"
    print $"   ($batch_list)"
    print $"   ($batch_status)"
    print $"   ($batch_monitor)"
    print $"   ($batch_rollback)"
    print $"   ($batch_cancel)"
    print $"   ($batch_stats)\n"

    let tip = (get-help-string "help-orch-tip")
    let example = (get-help-string "help-orch-example")

    print $"💡 ($tip)"
    print $"📝 ($example)\n"
}

# Placeholder implementations for other categories
def help-development [] {
    print "🧩 Development Category (documentation coming)"
}

def help-workspace [] {
    print "📁 Workspace Category (documentation coming)"
}

def help-platform [] {
    let title = (get-help-string "help-platform-title")
    print $"
╔════════════════════════════════════════════════════════════════╗
║ ($title) ║
╚════════════════════════════════════════════════════════════════╝
"

    # Lifecycle Commands
    let start = (get-help-string "help-plat-start")
    let start_local = (get-help-string "help-plat-start-local")
    let stop = (get-help-string "help-plat-stop")
    let status = (get-help-string "help-plat-status")
    let health = (get-help-string "help-plat-health")
    let check = (get-help-string "help-plat-check")

    print $"🎛️  Lifecycle"
    print $"   provisioning platform start [mode]     ($start)"
    print $"   provisioning platform start local      ($start_local)"
    print $"   provisioning platform stop             ($stop)"
    print $"   provisioning platform status           ($status)"
    print $"   provisioning platform health           ($health)"
    print $"   provisioning platform check            ($check)\n"

    # Discovery Commands
    let list = (get-help-string "help-plat-list")
    let connections = (get-help-string "help-plat-connections")
    let init = (get-help-string "help-plat-init")

    print $"🔍 Discovery"
    print $"   provisioning platform list             ($list)"
    print $"   provisioning platform connections      ($connections)"
    print $"   provisioning platform init             ($init)\n"

    # External Services
    let db = (get-help-string "help-plat-external-db")
    let oci = (get-help-string "help-plat-external-oci")
    let git = (get-help-string "help-plat-external-git")
    let cache = (get-help-string "help-plat-external-cache")

    print $"🌍 External Services Required"
    print $"   • Database:        ($db)"
    print $"   • OCI Registry:    ($oci)"
    print $"   • Git Source:      ($git)"
    print $"   • Cache:           ($cache)\n"

    let tip = (get-help-string "help-plat-tip")
    print $"💡 Tip: ($tip)\n"

    print "Examples:"
    print "   provisioning platform check           # Validate external services"
    print "   provisioning platform start           # Start platform (requires external services)"
    print "   provisioning platform status          # Show service status"
    print "   provisioning platform list            # List all services\n"
}

def help-setup [] {
    print "⚙️ Setup Category (documentation coming)"
}

def help-authentication [] {
    print "🔐 Authentication Category (documentation coming)"
}

def help-mfa [] {
    print "🔐 MFA Category (documentation coming)"
}

def help-plugins [] {
    print "🔌 Plugins Category (documentation coming)"
}

def help-utilities [] {
    print "🔧 Utilities Category (documentation coming)"
}

def help-tools [] {
    print "🛠️ Tools Category (documentation coming)"
}

def help-vm [] {
    print "💻 VM Category (documentation coming)"
}

def help-diagnostics [] {
    print "📊 Diagnostics Category (documentation coming)"
}

def help-concepts [] {
    print "💡 Concepts Category (documentation coming)"
}

def help-guides [] {
    print "📖 Guides Category (documentation coming)"
}

def help-integrations [] {
    print "🌐 Integrations Category (documentation coming)"
}
