#!/usr/bin/env nu

# Integration test for syntaxis installation
# Tests Phases 1-4: Config, Wrappers, Manifest, and Documentation

def test_header [title: string] {
    print ""
    print "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    print $"🧪 ($title)"
    print "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
}

def test_section [name: string] {
    print ""
    print $"   📝 ($name)"
}

def test_pass [message: string] {
    print $"   ✅ ($message)"
}

def test_fail [message: string] {
    print $"   ❌ ($message)"
}

def test_info [message: string] {
    print $"   ℹ️  ($message)"
}

# Phase 1: Configuration Files
def test_phase_1 [] {
    test_header "Phase 1: Configuration Files"

    test_section "Main config file"
    let template_main = "syntaxis/workspace-api-config.template.toml"
    if ($template_main | path exists) {
        test_pass "Found main config template"
        let size = (ls $template_main | get 0.size)
        test_info $"Size: ($size) bytes"
    } else {
        test_fail "Main config template not found"
        return false
    }

    test_section "Feature config files"
    let features_dir = "syntaxis/configs/features"
    if ($features_dir | path exists) {
        test_pass "Features directory exists"
        let templates = (ls $features_dir | where name ends-with ".template" | length)
        test_info $"Found ($templates) feature templates"

        if ($templates >= 4) {
            test_pass "All required feature configs present"
        } else {
            test_fail $"Expected 4+ feature configs, found ($templates)"
            return false
        }
    } else {
        test_fail "Features directory not found"
        return false
    }

    test_section "Config file syntax"
    # Validate TOML syntax (simple check)
    try {
        let main_content = (open $template_main)
        test_pass "Main config has valid TOML syntax"
    } catch {
        test_fail "Main config has invalid TOML syntax"
        return false
    }

    test_pass "✨ Phase 1 Complete: Configuration files ready"
    return true
}

# Phase 2: Wrapper Scripts
def test_phase_2 [] {
    test_header "Phase 2: Wrapper Scripts"

    let home = $env.HOME
    let cargo_bin = $"($home)/.cargo/bin"

    test_section "Wrapper script for workspace"
    let workspace_wrapper = $"($cargo_bin)/workspace"
    if ($workspace_wrapper | path exists) {
        test_pass "workspace wrapper exists"

        # Check if it's a NuShell script
        let is_nushell = (open $workspace_wrapper | str starts-with "#!/usr/bin/env nu")
        if $is_nushell {
            test_pass "workspace wrapper is valid NuShell script"
        } else {
            test_fail "workspace wrapper is not a NuShell script"
            return false
        }

        # Check for config discovery logic
        let has_config_search = (open $workspace_wrapper | str contains "config_paths")
        if $has_config_search {
            test_pass "workspace wrapper has config discovery logic"
        } else {
            test_fail "workspace wrapper missing config discovery logic"
            return false
        }
    } else {
        test_info "workspace wrapper not yet installed (expected if not run install)"
    }

    test_section "Wrapper script for workspace-tui"
    let tui_wrapper = $"($cargo_bin)/workspace-tui"
    if ($tui_wrapper | path exists) {
        test_pass "workspace-tui wrapper exists"

        let is_nushell = (open $tui_wrapper | str starts-with "#!/usr/bin/env nu")
        if $is_nushell {
            test_pass "workspace-tui wrapper is valid NuShell script"
        } else {
            test_fail "workspace-tui wrapper is not a NuShell script"
            return false
        }
    } else {
        test_info "workspace-tui wrapper not yet installed"
    }

    test_section "Real binary renaming"
    let workspace_real = $"($cargo_bin)/workspace.real"
    if ($workspace_real | path exists) {
        test_pass "workspace.real binary exists"
    } else {
        test_info "workspace.real not yet installed"
    }

    test_pass "✨ Phase 2 Complete: Wrapper scripts ready"
    return true
}

# Phase 3: Installation Manifest
def test_phase_3 [] {
    test_header "Phase 3: Installation Manifest"

    let manifest_path = ".syntaxis/manifest.toml"

    test_section "Manifest file"
    if ($manifest_path | path exists) {
        test_pass "Installation manifest exists"

        # Read manifest as string (not parsed TOML)
        let content = (cat $manifest_path)

        # Check required sections (accept both old and new formats)
        let has_installation = ($content | str contains "[installation]")
        let has_created_at = ($content | str contains "created_at")

        if ($has_installation or $has_created_at) {
            test_pass "Manifest contains installation metadata"
        } else {
            test_fail "Manifest missing installation metadata"
            return false
        }

        let has_binaries = ($content | str contains "[binaries")
        if $has_binaries {
            test_pass "Manifest contains [binaries] section"
        } else {
            test_fail "Manifest missing [binaries] section"
            return false
        }

        let has_configurations = ($content | str contains "[configurations")
        if $has_configurations {
            test_pass "Manifest contains [configurations] section"
        } else {
            test_fail "Manifest missing [configurations] section"
            return false
        }

        # Verification section is optional (only in new format)
        let has_verification = ($content | str contains "[verification]")
        if $has_verification {
            test_pass "Manifest contains [verification] section (enhanced format)"
        } else {
            test_info "Manifest uses basic format (will upgrade on next install)"
        }

        # Check for checksums (only in new format)
        let has_checksums = ($content | str contains "checksum")
        if $has_checksums {
            test_pass "Manifest includes integrity checksums (enhanced format)"
        } else {
            test_info "Manifest doesn't include checksums (will add on next install)"
        }
    } else {
        test_info "Installation manifest not yet created (expected if not run install)"
    }

    test_pass "✨ Phase 3 Complete: Manifest structure valid"
    return true
}

# Phase 4: Documentation
def test_phase_4 [] {
    test_header "Phase 4: Documentation"

    test_section "INSTALLATION_GUIDE.md"
    if ("INSTALLATION_GUIDE.md" | path exists) {
        test_pass "INSTALLATION_GUIDE.md exists"

        let content = (open "INSTALLATION_GUIDE.md")

        # Check for key sections
        let has_quick_start = ($content | str contains "Quick Start")
        if $has_quick_start {
            test_pass "Contains Quick Start section"
        } else {
            test_fail "Missing Quick Start section"
            return false
        }

        let has_commands = ($content | str contains "Installation Commands")
        if $has_commands {
            test_pass "Contains Installation Commands section"
        } else {
            test_fail "Missing Installation Commands section"
            return false
        }

        let has_troubleshooting = ($content | str contains "Troubleshooting")
        if $has_troubleshooting {
            test_pass "Contains Troubleshooting section"
        } else {
            test_fail "Missing Troubleshooting section"
            return false
        }
    } else {
        test_fail "INSTALLATION_GUIDE.md not found"
        return false
    }

    test_section "CONFIGURATION_GUIDE.md"
    if ("CONFIGURATION_GUIDE.md" | path exists) {
        test_pass "CONFIGURATION_GUIDE.md exists"

        let content = (open "CONFIGURATION_GUIDE.md")

        let has_hierarchy = ($content | str contains "Configuration Hierarchy")
        if $has_hierarchy {
            test_pass "Contains Configuration Hierarchy section"
        } else {
            test_fail "Missing Configuration Hierarchy section"
            return false
        }

        let has_main_config = ($content | str contains "workspace-api.toml")
        if $has_main_config {
            test_pass "Documents main configuration file"
        } else {
            test_fail "Missing main configuration documentation"
            return false
        }

        let has_features = ($content | str contains "auth.toml")
        if $has_features {
            test_pass "Documents feature configurations"
        } else {
            test_fail "Missing feature configuration documentation"
            return false
        }
    } else {
        test_fail "CONFIGURATION_GUIDE.md not found"
        return false
    }

    test_section "WRAPPER_DESIGN.md"
    if ("WRAPPER_DESIGN.md" | path exists) {
        test_pass "WRAPPER_DESIGN.md exists"

        let content = (open "WRAPPER_DESIGN.md")

        let has_overview = ($content | str contains "Overview")
        if $has_overview {
            test_pass "Contains Overview section"
        } else {
            test_fail "Missing Overview section"
            return false
        }

        let has_discovery = ($content | str contains "Configuration Discovery")
        if $has_discovery {
            test_pass "Documents configuration discovery"
        } else {
            test_fail "Missing configuration discovery documentation"
            return false
        }

        let has_env = ($content | str contains "Environment Variables")
        if $has_env {
            test_pass "Documents environment variables"
        } else {
            test_fail "Missing environment variables documentation"
            return false
        }

        let has_debugging = ($content | str contains "Debugging")
        if $has_debugging {
            test_pass "Contains debugging guide"
        } else {
            test_fail "Missing debugging guide"
            return false
        }
    } else {
        test_fail "WRAPPER_DESIGN.md not found"
        return false
    }

    test_pass "✨ Phase 4 Complete: Documentation complete"
    return true
}

# End-to-end test: Verify all phases work together
def test_integration [] {
    test_header "End-to-End Integration Test"

    test_section "Configuration discovery"
    let home = $env.HOME
    let config_dir = $"($home)/.config/syntaxis"

    if ($config_dir | path exists) {
        test_pass "Configuration directory exists"

        let main_config = $"($config_dir)/workspace-api.toml"
        if ($main_config | path exists) {
            test_pass "Main configuration deployed"
        } else {
            test_info "Main configuration not deployed (not yet installed)"
        }
    } else {
        test_info "Configuration directory not yet created"
    }

    test_section "Data directory"
    let data_dir = $"($home)/.local/share/syntaxis"
    if ($data_dir | path exists) {
        test_pass "Data directory exists and is ready"
    } else {
        test_info "Data directory not yet created (created on first run)"
    }

    test_section "Installation script"
    if ("scripts/install-cli.nu" | path exists) {
        test_pass "Installation script exists"

        let content = (open "scripts/install-cli.nu")
        let has_all_functions = (
            ($content | str contains "def deploy_configurations")
            and ($content | str contains "def create_wrappers")
            and ($content | str contains "def register_installations")
        )

        if $has_all_functions {
            test_pass "Installation script has all required functions"
        } else {
            test_fail "Installation script missing required functions"
            return false
        }
    } else {
        test_fail "Installation script not found"
        return false
    }

    test_pass "✨ Integration test complete: All systems ready"
    return true
}

# Main test runner
def main [] {
    print "🧪 syntaxis Installation Integration Tests"
    print "Starting comprehensive test suite..."
    print ""

    let phase1_ok = (test_phase_1)
    let phase2_ok = (test_phase_2)
    let phase3_ok = (test_phase_3)
    let phase4_ok = (test_phase_4)
    let integration_ok = (test_integration)

    # Summary
    print ""
    print "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    print "📊 Test Summary"
    print "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    print ""

    let phase1_status = if $phase1_ok { "✅" } else { "❌" }
    let phase2_status = if $phase2_ok { "✅" } else { "❌" }
    let phase3_status = if $phase3_ok { "✅" } else { "❌" }
    let phase4_status = if $phase4_ok { "✅" } else { "❌" }
    let integration_status = if $integration_ok { "✅" } else { "❌" }

    print ("Phase 1 [Configs]:        " + $phase1_status)
    print ("Phase 2 [Wrappers]:       " + $phase2_status)
    print ("Phase 3 [Manifest]:       " + $phase3_status)
    print ("Phase 4 [Documentation]:  " + $phase4_status)
    print ("Integration Test:         " + $integration_status)
    print ""

    let all_ok = ($phase1_ok and $phase2_ok and $phase3_ok and $phase4_ok and $integration_ok)

    if $all_ok {
        print "🎉 All tests passed! Installation system is ready."
        print ""
        print "Next steps:"
        print "  1. Run installation: just scripts-install all"
        print "  2. Check status: just scripts-install status"
        print "  3. Use binaries: syntaxis-cli --help"
        print ""
        exit 0
    } else {
        print "⚠️  Some tests failed. Review output above."
        print ""
        exit 1
    }
}

