#!/usr/bin/env nu

# Simplified Rule Validation Script for Rustelo Project
# Validates critical code changes against project constraints

def main [
    --path: string = "."     # Path to validate (default: current directory)
    --fix                    # Apply automatic fixes where possible
    --strict                 # Fail on warnings (not just errors)
] {
    print "🔍 Validating Rustelo project rules..."

    let violations = []

    # Check critical violations with basic pattern matching
    let violations = ($violations | append (check_basic_violations $path))

    # Display results
    if ($violations | is-empty) {
        print "✅ All rule validations passed!"
        return 0
    } else {
        print "❌ Rule violations found:"
        for $violation in $violations {
            print $"  🚫 ($violation.severity): ($violation.message)"
            if ($violation.file?) {
                print $"     File: ($violation.file)"
            }
            if ($violation.fix?) {
                print $"     Fix: ($violation.fix)"
            }
        }

        let errors = ($violations | where severity == "ERROR")
        if not ($errors | is-empty) {
            return 1
        } else if $strict {
            return 1
        } else {
            return 0
        }
    }
}

# Basic validation checks
def check_basic_violations [path: string] {
    let violations = []

    # Check for Leptos router usage (most critical)
    try {
        if (has_command "rg") {
            let leptos_check = (^rg -l "leptos_router" --type rust $path | lines)
            if not ($leptos_check | is-empty) {
                let violations = ($violations | append {
                    severity: "ERROR"
                    message: "Leptos router found - this project uses custom routing"
                    file: ($leptos_check | get 0? | default "unknown")
                    fix: "Remove leptos_router usage, use custom routing system"
                })
            }
        }

        # Check for unwrap() usage
        if (has_command "rg") {
            let unwrap_check = (^rg -l "unwrap()" --type rust $path | lines)
            if not ($unwrap_check | is-empty) {
                let violations = ($violations | append {
                    severity: "ERROR"
                    message: "unwrap() usage found - use proper error handling"
                    file: ($unwrap_check | get 0? | default "unknown")
                    fix: "Use ? operator or proper error handling"
                })
            }
        }

        $violations
    } catch {
        # If rg fails, return empty violations (don't block development)
        print "⚠️  Warning: Could not run full validation (rg not available)"
        []
    }
}

# Helper to check if command exists
def has_command [cmd: string] {
    which $cmd | is-not-empty
}
