#!/usr/bin/env nu
# Syntaxis API wrapper script
# This script provides a unified interface to manage syntaxis-api using provctl.
#
# provctl handles:
# - Multi-platform service management (systemd, launchd, pidfile)
# - Process lifecycle (start, stop, restart, status)
# - Logging and monitoring
# - Cross-platform configuration
#
# See: /Users/Akasha/Development/provctl/ for more information

# Source shared libraries - they should be in NU_LIB_DIRS
source syntaxis-lib.nu
source syntaxis-api-lib.nu

$env.SYNTAXIS_CONFIG_DIR = ($env.HOME | path join ".config/syntaxis")

# Setup environment for auto-discovery config loading
$env.SYNTAXIS_DATA_DIR = $"($env.HOME)/.local/share/syntaxis"
$env.SYNTAXIS_PUBLIC_DIR = $"($env.HOME)/.config/syntaxis/public"

# Verify provctl is available
def check_provctl [] {
    if (which provctl | is-empty) {
        print "❌ provctl not found. Please install it:"
        print "   cd /Users/Akasha/Development/provctl && ./install-provctl.nu"
        exit 1
    }
}

# Get the syntaxis-api configuration file
def get_config_file [] {
    let config_dir = ($env.HOME | path join ".config/syntaxis")

    if (($config_dir | path join "config.toml") | path exists) {
        $config_dir | path join "config.toml"
    } else if (($config_dir | path join "syntaxis-api.toml") | path exists) {
        $config_dir | path join "syntaxis-api.toml"
    } else {
        print $"🛑 Config path not found in ($config_dir)"
        print "   Create one of these files:"
        print "   - $config_dir/config.toml"
        print "   - $config_dir/syntaxis-api.toml"
        print ""
        print "   See /Users/Akasha/provctl/provisioning/examples/syntaxis-api.toml"
        exit 1
    }
}

# Start the syntaxis-api server using provctl
def start_server [] {
    check_provctl

    let config = (get_config_file)
    print "▶️  Starting syntaxis-api..."
    print "   Config: $config"

    try {
        # provctl will handle auto-detection and use the appropriate backend
        ^provctl start syntaxis-api
    } catch { |err|
        print $"❌ Failed to start syntaxis-api: ($err)"
        exit 1
    }
}

# Stop the syntaxis-api server using provctl
def stop_server [] {
    check_provctl

    print "⏹️  Stopping syntaxis-api..."

    try {
        ^provctl stop syntaxis-api
    } catch { |err|
        print $"❌ Failed to stop syntaxis-api: ($err)"
        exit 1
    }
}

# Check syntaxis-api status using provctl
def check_status [] {
    check_provctl

    try {
        ^provctl status syntaxis-api
    } catch { |err|
        print $"❌ Failed to check status: ($err)"
        exit 1
    }
}

# View syntaxis-api logs using provctl
def view_logs [lines: int = 50] {
    check_provctl

    try {
        print $"📋 Last ($lines) log lines:"
        print ""
        ^provctl logs syntaxis-api --lines $lines
    } catch { |err|
        print $"❌ Failed to view logs: ($err)"
        exit 1
    }
}

# Restart the syntaxis-api server using provctl
def restart_server [] {
    check_provctl

    print "🔄 Restarting syntaxis-api..."

    try {
        ^provctl restart syntaxis-api
    } catch { |err|
        print $"❌ Failed to restart syntaxis-api: ($err)"
        exit 1
    }
}

def main [...args] {
    # Handle no arguments
    if ($args | length) == 0 {
        api_usage
        return
    }

    let command = $args | first
    let remaining = ($args | skip 1)

    match $command {
        "start" => {
            start_server
        }
        "stop" => {
            stop_server
        }
        "restart" => {
            restart_server
        }
        "status" => {
            check_status
        }
        "logs" => {
            # Parse optional --lines argument
            let lines = if ($remaining | length) > 0 and (($remaining | first) == "--lines") {
                ($remaining | get 1 | into int)
            } else {
                50
            }
            view_logs $lines
        }
        "help" | "--help" | "-h" => {
            api_usage
        }
        _ => {
            print $"❌ Unknown command: ($command)"
            print ""
            api_usage
            exit 1
        }
    }
}
