#!/usr/bin/env nu

# Start KMS Service
# Manages the KMS service lifecycle

def main [
    --background  # Run in background
    --check       # Check if service is running
    --stop        # Stop the service
    --restart     # Restart the service
    --logs        # Show logs
] {
    let service_name = "kms-service"
    let pid_file = "./data/kms-service.pid"
    let log_file = "./data/kms-service.log"

    if $check {
        check_service $pid_file
        return
    }

    if $stop {
        stop_service $pid_file $service_name
        return
    }

    if $restart {
        stop_service $pid_file $service_name
        sleep 2sec
        start_service $background $pid_file $log_file
        return
    }

    if $logs {
        if ($log_file | path exists) {
            tail -f $log_file
        } else {
            print "No logs found"
        }
        return
    }

    start_service $background $pid_file $log_file
}

def start_service [background: bool, pid_file: string, log_file: string] {
    # Check if already running
    if ($pid_file | path exists) {
        let pid = open $pid_file | str trim | into int
        if (ps | where pid == $pid | length) > 0 {
            print $"✗ KMS service is already running \(PID: ($pid)\)"
            return
        } else {
            rm $pid_file
        }
    }

    # Ensure data directory exists
    mkdir data

    # Build if needed
    if not ("./target/release/kms-service" | path exists) {
        print "Building KMS service..."
        cargo build --release
    }

    # Load configuration
    let config_path = $env.KMS_CONFIG_PATH? | default "../../config/kms.toml"

    if not ($config_path | path exists) {
        print $"✗ Configuration file not found: ($config_path)"
        print "  Create it from the example: cp ../../config/kms.toml.example ../../config/kms.toml"
        return
    }

    print "Starting KMS service..."

    if $background {
        # Start in background
        let process = bash -c $"./target/release/kms-service > ($log_file) 2>&1 & echo $!"
        let pid = $process | str trim | into int
        $pid | save $pid_file

        sleep 2sec

        # Check if started successfully
        if (ps | where pid == $pid | length) > 0 {
            print $"✓ KMS service started in background \(PID: ($pid)\)"
            print $"  Logs: ($log_file)"
            print "  Check status: ./scripts/start-kms.nu --check"
        } else {
            print "✗ KMS service failed to start"
            print "  Check logs: cat ($log_file)"
        }
    } else {
        # Run in foreground
        ./target/release/kms-service
    }
}

def stop_service [pid_file: string, service_name: string] {
    if not ($pid_file | path exists) {
        print "✗ KMS service is not running"
        return
    }

    let pid = open $pid_file | str trim | into int
    print $"Stopping KMS service \(PID: ($pid)\)..."

    kill $pid

    sleep 1sec

    if (ps | where pid == $pid | length) > 0 {
        print "Force killing..."
        kill -9 $pid
    }

    rm $pid_file
    print "✓ KMS service stopped"
}

def check_service [pid_file: string] {
    if not ($pid_file | path exists) {
        print "✗ KMS service is not running"
        return
    }

    let pid = open $pid_file | str trim | into int

    if (ps | where pid == $pid | length) > 0 {
        print $"✓ KMS service is running \(PID: ($pid)\)"

        # Check health endpoint
        try {
            let health = http get "http://localhost:8081/api/v1/kms/health" | from json
            print $"  Status: ($health.status)"
            print $"  Backend: ($health.backend)"
        } catch {
            print "  ⚠ Health check failed - service may be starting"
        }
    } else {
        print $"✗ KMS service is not running \(stale PID file: ($pid)\)"
        rm $pid_file
    }
}
