#!/usr/bin/env nu

# Manifest management utilities for .syntaxis/manifest.toml
#
# Functions to read, write, and manipulate manifest.toml files
# that track installed binaries and configurations in syntaxis.

use scripts/common/find-config.nu [find-config]

# Load manifest from .syntaxis/manifest.toml
export def load-manifest []: nothing -> record {
    let manifest_path = ".syntaxis/manifest.toml"

    if not ($manifest_path | path exists) {
        return {
            syntaxis: {
                version: "0.1.0"
                created_at: (date now | format date "%Y-%m-%d")
                installation_root: (pwd)
            }
            binaries: {}
            configurations: {}
        }
    }

    try {
        open $manifest_path
    } catch {
        print $"⚠️  Failed to parse manifest.toml: ($in)"
        {}
    }
}

# Save manifest to .syntaxis/manifest.toml
export def save-manifest [manifest: record] {
    let manifest_path = ".syntaxis/manifest.toml"
    mkdir -p ".syntaxis"

    try {
        let content = (manifest_to_toml $manifest)
        $content | save --force $manifest_path
        print $"✓ Saved manifest to ($manifest_path)"
    } catch {
        print $"❌ Failed to save manifest: ($in)"
    }
}

# Convert manifest record to TOML format
def manifest_to_toml [manifest: record]: nothing -> string {
    mut output = "# syntaxis Installation Manifest\n"
    output += "# This file tracks installed binaries and configurations\n\n"

    # Add syntaxis section
    output += "[syntaxis]\n"
    output += $"version = \"($manifest.syntaxis.version)\"\n"
    output += $"created_at = \"($manifest.syntaxis.created_at)\"\n"
    output += $"installation_root = \"($manifest.syntaxis.installation_root)\"\n"
    output += "\n"

    # Add binaries section
    output += "[binaries]\n"
    if ($manifest.binaries | type) == "record" {
        $manifest.binaries | each { |key, value|
            output += $"($key) = { "
            output += $"enabled = ($value.enabled), "
            output += $"installed_at = \"($value.installed_at)\", "
            output += $"version = \"($value.version)\", "
            output += $"path = \"($value.path)\""
            output += " }\n"
        }
    }
    output += "\n"

    # Add configurations section
    output += "[configurations]\n"
    if ($manifest.configurations | type) == "record" {
        $manifest.configurations | each { |key, value|
            output += $"($key) = { "
            output += $"enabled = ($value.enabled), "
            output += $"type = \"($value.type)\", "
            output += $"path = \"($value.path)\""
            output += " }\n"
        }
    }

    $output
}

# List all installed binaries from manifest
export def list-binaries [] {
    let manifest = load-manifest

    if ($manifest.binaries | is-empty) {
        print "No binaries found in manifest"
        return
    }

    print ""
    print "📦 Installed Binaries:"
    print ""

    $manifest.binaries | each { |key, value|
        let status = if $value.enabled { "✅" } else { "⭕" }
        print $"  ($status) ($key)"
        print $"     Installed: ($value.installed_at)"
        print $"     Version: ($value.version)"
        print $"     Path: ($value.path)"
        print ""
    }
}

# Register a binary installation in manifest
export def register-binary [name: string, version: string, path: string] {
    mut manifest = load-manifest

    let binary_record = {
        enabled: true
        installed_at: (date now | format date "%Y-%m-%d %H:%M:%S")
        version: $version
        path: $path
    }

    if ($manifest.binaries | type) != "record" {
        $manifest.binaries = {}
    }

    $manifest.binaries = ($manifest.binaries | insert $name $binary_record)
    save-manifest $manifest

    print $"✓ Registered binary: ($name)"
}

# Unregister a binary from manifest
export def unregister-binary [name: string] {
    mut manifest = load-manifest

    if ($name not-in $manifest.binaries) {
        print $"⚠️  Binary not found: ($name)"
        return
    }

    $manifest.binaries = ($manifest.binaries | del $name)
    save-manifest $manifest

    print $"✓ Unregistered binary: ($name)"
}

# Enable a binary
export def enable-binary [name: string] {
    mut manifest = load-manifest

    if ($name not-in $manifest.binaries) {
        print $"❌ Binary not found: ($name)"
        return
    }

    mut binary = ($manifest.binaries | get $name)
    $binary.enabled = true
    $manifest.binaries = ($manifest.binaries | insert $name $binary)
    save-manifest $manifest

    print $"✓ Enabled: ($name)"
}

# Disable a binary
export def disable-binary [name: string] {
    mut manifest = load-manifest

    if ($name not-in $manifest.binaries) {
        print $"❌ Binary not found: ($name)"
        return
    }

    mut binary = ($manifest.binaries | get $name)
    $binary.enabled = false
    $manifest.binaries = ($manifest.binaries | insert $name $binary)
    save-manifest $manifest

    print $"✓ Disabled: ($name)"
}

# List all configurations from manifest
export def list-configs [] {
    let manifest = load-manifest

    if ($manifest.configurations | is-empty) {
        print "No configurations found in manifest"
        return
    }

    print ""
    print "⚙️  Configurations:"
    print ""

    $manifest.configurations | each { |key, value|
        let status = if $value.enabled { "✅" } else { "⭕" }
        print $"  ($status) ($key)"
        print $"     Type: ($value.type)"
        print $"     Path: ($value.path)"
        print ""
    }
}

# Register a configuration
export def register-config [name: string, type: string, path: string] {
    mut manifest = load-manifest

    let config_record = {
        enabled: true
        type: $type
        path: $path
    }

    if ($manifest.configurations | type) != "record" {
        $manifest.configurations = {}
    }

    $manifest.configurations = ($manifest.configurations | insert $name $config_record)
    save-manifest $manifest

    print $"✓ Registered configuration: ($name)"
}

# Show full manifest
export def show-manifest [] {
    let manifest = load-manifest

    print ""
    print "📋 Full Manifest"
    print ""

    print "Syntaxis:"
    print $"  Version: ($manifest.syntaxis.version)"
    print $"  Created: ($manifest.syntaxis.created_at)"
    print ""

    list-binaries
    list-configs
}

# Test function
def test-manifest [] {
    true
}
