# Report Generator
# Generates validation reports in various formats (Markdown, YAML, JSON)

# Generate Markdown Report
export def generate_markdown_report [results: record, context: record]: nothing -> string {
    let summary = $results.summary
    let issues = $results.issues
    let timestamp = (date now | format date "%Y-%m-%d %H:%M:%S")
    let infra_name = ($context.infra_path | path basename)

    mut report = ""

    # Header
    $report = $report + $"# Infrastructure Validation Report\n\n"
    $report = $report + $"**Date:** ($timestamp)\n"
    $report = $report + $"**Infrastructure:** ($infra_name)\n"
    $report = $report + $"**Path:** ($context.infra_path)\n\n"

    # Summary section
    $report = $report + "## Summary\n\n"

    let critical_count = ($issues | where severity == "critical" | length)
    let error_count = ($issues | where severity == "error" | length)
    let warning_count = ($issues | where severity == "warning" | length)
    let info_count = ($issues | where severity == "info" | length)

    $report = $report + $"- ✅ **Passed:** ($summary.passed)/($summary.total_checks)\n"

    if $critical_count > 0 {
        $report = $report + $"- 🚨 **Critical:** ($critical_count)\n"
    }
    if $error_count > 0 {
        $report = $report + $"- ❌ **Errors:** ($error_count)\n"
    }
    if $warning_count > 0 {
        $report = $report + $"- ⚠️ **Warnings:** ($warning_count)\n"
    }
    if $info_count > 0 {
        $report = $report + $"- ℹ️ **Info:** ($info_count)\n"
    }
    if $summary.auto_fixed > 0 {
        $report = $report + $"- 🔧 **Auto-fixed:** ($summary.auto_fixed)\n"
    }

    $report = $report + "\n"

    # Overall status
    if $critical_count > 0 {
        $report = $report + "🚨 **Status:** CRITICAL ISSUES FOUND - Deployment should be blocked\n\n"
    } else if $error_count > 0 {
        $report = $report + "❌ **Status:** ERRORS FOUND - Issues need resolution\n\n"
    } else if $warning_count > 0 {
        $report = $report + "⚠️ **Status:** WARNINGS FOUND - Review recommended\n\n"
    } else {
        $report = $report + "✅ **Status:** ALL CHECKS PASSED\n\n"
    }

    # Issues by severity
    if $critical_count > 0 {
        $report = $report + "## 🚨 Critical Issues\n\n"
        $report = $report + (generate_issues_section ($issues | where severity == "critical"))
    }

    if $error_count > 0 {
        $report = $report + "## ❌ Errors\n\n"
        $report = $report + (generate_issues_section ($issues | where severity == "error"))
    }

    if $warning_count > 0 {
        $report = $report + "## ⚠️ Warnings\n\n"
        $report = $report + (generate_issues_section ($issues | where severity == "warning"))
    }

    if $info_count > 0 {
        $report = $report + "## ℹ️ Information\n\n"
        $report = $report + (generate_issues_section ($issues | where severity == "info"))
    }

    # Files processed
    $report = $report + "## 📁 Files Processed\n\n"
    for file in $results.files_processed {
        let relative_path = ($file | str replace $context.infra_path "")
        $report = $report + $"- `($relative_path)`\n"
    }
    $report = $report + "\n"

    # Auto-fixes applied
    if $summary.auto_fixed > 0 {
        $report = $report + "## 🔧 Auto-fixes Applied\n\n"
        let auto_fixed_issues = ($issues | where auto_fixed? == true)
        for issue in $auto_fixed_issues {
            let relative_path = ($issue.file | str replace $context.infra_path "")
            $report = $report + $"- **($issue.rule_id)** in `($relative_path)`: ($issue.message)\n"
        }
        $report = $report + "\n"
    }

    # Validation context
    $report = $report + "## 🔧 Validation Context\n\n"
    $report = $report + $"- **Fix mode:** ($context.fix_mode)\n"
    $report = $report + $"- **Dry run:** ($context.dry_run)\n"
    $report = $report + $"- **Severity filter:** ($context.severity_filter)\n"
    $report = $report + $"- **CI mode:** ($context.ci_mode)\n"

    $report
}

def generate_issues_section [issues: list]: nothing -> string {
    mut section = ""

    for issue in $issues {
        let relative_path = ($issue.file | str replace --all "/Users/Akasha/repo-cnz/src/provisioning/" "" | str replace --all "/Users/Akasha/repo-cnz/" "")

        $section = $section + $"### ($issue.rule_id): ($issue.message)\n\n"
        $section = $section + $"**File:** `($relative_path)`\n"

        if ($issue.line | is-not-empty) {
            $section = $section + $"**Line:** ($issue.line)\n"
        }

        if ($issue.details | is-not-empty) {
            $section = $section + $"**Details:** ($issue.details)\n"
        }

        if ($issue.suggested_fix | is-not-empty) {
            $section = $section + $"**Suggested Fix:** ($issue.suggested_fix)\n"
        }

        if ($issue.auto_fixed? | default false) {
            $section = $section + $"**Status:** ✅ Auto-fixed\n"
        } else if ($issue.auto_fixable | default false) {
            $section = $section + "**Auto-fixable:** Yes (use --fix flag)\n"
        }

        $section = $section + "\n"
    }

    $section
}

# Generate YAML Report
export def generate_yaml_report [results: record, context: record]: nothing -> string {
    let timestamp = (date now | format date "%Y-%m-%dT%H:%M:%SZ")
    let infra_name = ($context.infra_path | path basename)

    let report_data = {
        validation_report: {
            metadata: {
                timestamp: $timestamp
                infra: $infra_name
                infra_path: $context.infra_path
                validator_version: "1.0.0"
                context: {
                    fix_mode: $context.fix_mode
                    dry_run: $context.dry_run
                    severity_filter: $context.severity_filter
                    ci_mode: $context.ci_mode
                    report_format: $context.report_format
                }
            }
            summary: {
                total_checks: $results.summary.total_checks
                passed: $results.summary.passed
                failed: $results.summary.failed
                auto_fixed: $results.summary.auto_fixed
                skipped: $results.summary.skipped
                by_severity: {
                    critical: ($results.issues | where severity == "critical" | length)
                    error: ($results.issues | where severity == "error" | length)
                    warning: ($results.issues | where severity == "warning" | length)
                    info: ($results.issues | where severity == "info" | length)
                }
            }
            issues: ($results.issues | each {|issue|
                {
                    id: $issue.rule_id
                    severity: $issue.severity
                    message: $issue.message
                    file: ($issue.file | str replace $context.infra_path "")
                    line: $issue.line
                    details: $issue.details
                    suggested_fix: $issue.suggested_fix
                    auto_fixable: ($issue.auto_fixable | default false)
                    auto_fixed: ($issue.auto_fixed? | default false)
                    variable_name: ($issue.variable_name? | default null)
                }
            })
            files_processed: ($results.files_processed | each {|file|
                ($file | str replace $context.infra_path "")
            })
        }
    }

    ($report_data | to yaml)
}

# Generate JSON Report
export def generate_json_report [results: record, context: record]: nothing -> string {
    let timestamp = (date now | format date "%Y-%m-%dT%H:%M:%SZ")
    let infra_name = ($context.infra_path | path basename)

    let report_data = {
        validation_report: {
            metadata: {
                timestamp: $timestamp
                infra: $infra_name
                infra_path: $context.infra_path
                validator_version: "1.0.0"
                context: {
                    fix_mode: $context.fix_mode
                    dry_run: $context.dry_run
                    severity_filter: $context.severity_filter
                    ci_mode: $context.ci_mode
                    report_format: $context.report_format
                }
            }
            summary: {
                total_checks: $results.summary.total_checks
                passed: $results.summary.passed
                failed: $results.summary.failed
                auto_fixed: $results.summary.auto_fixed
                skipped: $results.summary.skipped
                by_severity: {
                    critical: ($results.issues | where severity == "critical" | length)
                    error: ($results.issues | where severity == "error" | length)
                    warning: ($results.issues | where severity == "warning" | length)
                    info: ($results.issues | where severity == "info" | length)
                }
            }
            issues: ($results.issues | each {|issue|
                {
                    id: $issue.rule_id
                    severity: $issue.severity
                    message: $issue.message
                    file: ($issue.file | str replace $context.infra_path "")
                    line: $issue.line
                    details: $issue.details
                    suggested_fix: $issue.suggested_fix
                    auto_fixable: ($issue.auto_fixable | default false)
                    auto_fixed: ($issue.auto_fixed? | default false)
                    variable_name: ($issue.variable_name? | default null)
                }
            })
            files_processed: ($results.files_processed | each {|file|
                ($file | str replace $context.infra_path "")
            })
        }
    }

    ($report_data | to json --indent 2)
}

# Generate CI/CD friendly summary
export def generate_ci_summary [results: record]: nothing -> string {
    let summary = $results.summary
    let critical_count = ($results.issues | where severity == "critical" | length)
    let error_count = ($results.issues | where severity == "error" | length)
    let warning_count = ($results.issues | where severity == "warning" | length)

    mut output = ""

    $output = $output + $"VALIDATION_TOTAL_CHECKS=($summary.total_checks)\n"
    $output = $output + $"VALIDATION_PASSED=($summary.passed)\n"
    $output = $output + $"VALIDATION_FAILED=($summary.failed)\n"
    $output = $output + $"VALIDATION_AUTO_FIXED=($summary.auto_fixed)\n"
    $output = $output + $"VALIDATION_CRITICAL=($critical_count)\n"
    $output = $output + $"VALIDATION_ERRORS=($error_count)\n"
    $output = $output + $"VALIDATION_WARNINGS=($warning_count)\n"

    if $critical_count > 0 {
        $output = $output + "VALIDATION_STATUS=CRITICAL\n"
        $output = $output + "VALIDATION_EXIT_CODE=1\n"
    } else if $error_count > 0 {
        $output = $output + "VALIDATION_STATUS=ERROR\n"
        $output = $output + "VALIDATION_EXIT_CODE=2\n"
    } else if $warning_count > 0 {
        $output = $output + "VALIDATION_STATUS=WARNING\n"
        $output = $output + "VALIDATION_EXIT_CODE=3\n"
    } else {
        $output = $output + "VALIDATION_STATUS=PASSED\n"
        $output = $output + "VALIDATION_EXIT_CODE=0\n"
    }

    $output
}

# Generate enhancement suggestions report
export def generate_enhancement_report [results: record, context: record]: nothing -> string {
    let infra_name = ($context.infra_path | path basename)
    let warnings = ($results.issues | where severity == "warning")
    let info_items = ($results.issues | where severity == "info")

    mut report = ""

    $report = $report + $"# Infrastructure Enhancement Suggestions\n\n"
    $report = $report + $"**Infrastructure:** ($infra_name)\n"
    $report = $report + $"**Generated:** (date now | format date '%Y-%m-%d %H:%M:%S')\n\n"

    if ($warnings | length) > 0 {
        $report = $report + "## ⚠️ Recommended Improvements\n\n"
        for warning in $warnings {
            let relative_path = ($warning.file | str replace $context.infra_path "")
            $report = $report + $"- **($warning.rule_id)** in `($relative_path)`: ($warning.message)\n"
            if ($warning.suggested_fix | is-not-empty) {
                $report = $report + $"  - Suggestion: ($warning.suggested_fix)\n"
            }
        }
        $report = $report + "\n"
    }

    if ($info_items | length) > 0 {
        $report = $report + "## ℹ️ Best Practice Suggestions\n\n"
        for info in $info_items {
            let relative_path = ($info.file | str replace $context.infra_path "")
            $report = $report + $"- **($info.rule_id)** in `($relative_path)`: ($info.message)\n"
            if ($info.suggested_fix | is-not-empty) {
                $report = $report + $"  - Suggestion: ($info.suggested_fix)\n"
            }
        }
        $report = $report + "\n"
    }

    if ($warnings | length) == 0 and ($info_items | length) == 0 {
        $report = $report + "✅ No enhancement suggestions at this time. Your infrastructure follows current best practices!\n"
    }

    $report
}