# Integration Test Environment Teardown
# Cleans up test resources from OrbStack machine

use std log
use framework/test_helpers.nu *
use framework/orbstack_helpers.nu *

# Main teardown function
export def main [
    --force: bool = false  # Skip confirmation prompts
    --keep-workspace: bool = false  # Keep test workspace for debugging
    --keep-logs: bool = false  # Keep service logs
] {
    log info "Tearing down integration test environment..."

    if not $force {
        print "This will remove all test resources from OrbStack. Continue? [y/N]: "
        let response = (input)

        if $response != "y" and $response != "Y" {
            log info "Teardown cancelled"
            return
        }
    }

    # Load test configuration
    let test_config = (load-test-config)

    # Collect logs before cleanup (if requested)
    if $keep_logs {
        collect-service-logs $test_config
    }

    # Cleanup OrbStack containers and networks
    cleanup-orbstack-resources $test_config

    # Cleanup test workspace
    if not $keep_workspace {
        cleanup-test-workspace $test_config
    }

    # Cleanup Docker volumes
    cleanup-docker-volumes

    log info "Test environment teardown completed"

    {
        status: "cleaned"
        workspace_kept: $keep_workspace
        logs_kept: $keep_logs
        timestamp: (date now)
    }
}

# Collect service logs before cleanup
def collect-service-logs [test_config: record] {
    log info "Collecting service logs..."

    let log_dir = $"($test_config.reporting.output_dir)/logs"
    mkdir $log_dir

    let containers = [
        "orchestrator"
        "coredns"
        "oci-registry"
        "harbor"
        "gitea"
        "postgres"
        "prometheus"
        "grafana"
    ]

    for container in $containers {
        try {
            log info $"Collecting logs for: ($container)"

            let log_file = $"($log_dir)/($container).log"
            orbstack-logs $container --tail 1000 | save -f $log_file

            log info $"Logs saved: ($log_file)"
        } catch { |err|
            log warning $"Failed to collect logs for ($container): ($err.msg)"
        }
    }

    log info $"All logs collected in: ($log_dir)"
}

# Cleanup OrbStack resources
def cleanup-orbstack-resources [test_config: record] {
    log info "Cleaning up OrbStack resources..."

    orbstack-cleanup

    log info "OrbStack resources cleaned up"
}

# Cleanup test workspace
def cleanup-test-workspace [test_config: record] {
    log info "Cleaning up test workspace..."

    let workspace_path = $test_config.test_workspace.path

    if ($workspace_path | path exists) {
        rm -rf $workspace_path
        log info $"Removed test workspace: ($workspace_path)"
    }

    # Cleanup additional test workspaces created during testing
    for workspace in $test_config.test_data.workspaces {
        let workspace_path = $"($test_config.test_workspace.path)-($workspace.name)"

        if ($workspace_path | path exists) {
            rm -rf $workspace_path
            log info $"Removed test workspace: ($workspace_path)"
        }
    }
}

# Cleanup Docker volumes
def cleanup-docker-volumes [] {
    log info "Cleaning up Docker volumes..."

    let connection = (orbstack-connect)

    let volumes = [
        "zot-data"
        "gitea-data"
        "postgres-data"
        "prometheus-data"
        "grafana-data"
    ]

    for volume in $volumes {
        try {
            docker -H $connection.docker_socket volume rm $volume
            log info $"Removed volume: ($volume)"
        } catch {
            # Ignore errors if volume doesn't exist
        }
    }
}
