#!/usr/bin/env bash
# Generate Validation Report Script
# Creates comprehensive validation reports in both Markdown and JSON formats

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
PACKAGES_DIR="$PROJECT_ROOT/marketplace/packages"
REPORT_MD="$PROJECT_ROOT/marketplace/VALIDATION_REPORT.md"
REPORT_JSON="$PROJECT_ROOT/marketplace/validation_results.json"
cd "$PROJECT_ROOT"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log() {
    echo -e "${BLUE}[REPORT]${NC} $1"
}

success() {
    echo -e "${GREEN}✓${NC} $1"
}

error() {
    echo -e "${RED}✗${NC} $1"
}

# Check if ggen CLI is available
if ! command -v cargo &> /dev/null; then
    error "cargo not found. Please install Rust toolchain."
    exit 1
fi

# Build ggen CLI if needed
log "Building ggen CLI..."
if ! cargo build --release --bin ggen -p ggen-cli-lib &> /dev/null; then
    error "Failed to build ggen CLI"
    exit 1
fi

GGEN_BIN="$PROJECT_ROOT/target/release/ggen"
if [ ! -f "$GGEN_BIN" ]; then
    GGEN_BIN="$PROJECT_ROOT/target/debug/ggen"
fi

if [ ! -f "$GGEN_BIN" ]; then
    error "ggen binary not found. Build failed."
    exit 1
fi

success "ggen CLI ready: $GGEN_BIN"

# Run validation
log "Running validation on all packages..."
VALIDATION_OUTPUT=$("$GGEN_BIN" marketplace validate --packages-dir "$PACKAGES_DIR" --json 2>&1 || true)

# Generate JSON report
log "Generating JSON report..."
echo "$VALIDATION_OUTPUT" > "$REPORT_JSON"
success "JSON report saved: $REPORT_JSON"

# Generate Markdown report
log "Generating Markdown report..."

if command -v jq &> /dev/null && echo "$VALIDATION_OUTPUT" | jq . &> /dev/null; then
    TOTAL=$(echo "$VALIDATION_OUTPUT" | jq -r '.total_packages // 0')
    READY=$(echo "$VALIDATION_OUTPUT" | jq -r '.ready_count // 0')
    NEEDS_IMPROVEMENT=$(echo "$VALIDATION_OUTPUT" | jq -r '.needs_improvement_count // 0')
    NOT_READY=$(echo "$VALIDATION_OUTPUT" | jq -r '.not_ready_count // 0')
    
    READY_PCT=0
    if [ $TOTAL -gt 0 ]; then
        READY_PCT=$((READY * 100 / TOTAL))
    fi
    
    cat > "$REPORT_MD" <<EOF
# Marketplace Production Validation Report

**Generated**: $(date -u +"%Y-%m-%d %H:%M:%S UTC")
**Total Packages**: $TOTAL

## Executive Summary

| Status | Count | Percentage |
|--------|-------|------------|
| ✅ Production Ready | $READY | $READY_PCT% |
| ⚠️  Needs Improvement | $NEEDS_IMPROVEMENT | $((NEEDS_IMPROVEMENT * 100 / TOTAL))% |
| ❌ Not Ready | $NOT_READY | $((NOT_READY * 100 / TOTAL))% |

## Production Readiness Criteria

### Required Checks (Critical - 60% weight)
- ✅ **package.toml** - Complete metadata with version, description, license
- ✅ **README.md** - Documentation with examples
- ✅ **Source code** - At least \`src/main.rs\` or \`src/lib.rs\` exists (or templates/)
- ✅ **License file** - LICENSE, LICENSE-MIT, or LICENSE-APACHE present

### Quality Checks (Bonus - 40% weight)
- ✅ **RDF ontology** - \`rdf/ontology.ttl\` with 200+ lines (if applicable)
- ✅ **SPARQL queries** - \`sparql/*.rq\` files (if applicable)
- ✅ **Examples** - Runnable examples in \`examples/\` directory
- ✅ **Tests** - Test files in \`tests/\` directory
- ✅ **Documentation** - Additional docs in \`docs/\` directory

### Scoring
- **95%+**: Production ready ✅
- **80-94%**: Needs improvement ⚠️
- **<80%**: Not ready ❌

## Package Details

EOF

    # Add package details
    echo "$VALIDATION_OUTPUT" | jq -r '.all_results[]? | "### \(.package_name)\n\n- **Score**: \(.score | tostring | .[0:5])%\n- **Production Ready**: \(if .production_ready then "✅ Yes" else "❌ No" end)\n- **Errors**: \(.errors | length)\n- **Warnings**: \(.warnings | length)\n\n#### Required Checks\n\(.required_checks[] | "- \(.1.message)")\n\n#### Quality Checks\n\(.quality_checks[] | "- \(.1.message)")\n\n---\n"' >> "$REPORT_MD"
    
    # Add recommendations
    cat >> "$REPORT_MD" <<EOF

## Recommendations

### For Production Ready Packages ($READY)
- ✅ These packages meet all production readiness criteria
- Consider adding to CI/CD pipeline
- Ready for public release

### For Packages Needing Improvement ($NEEDS_IMPROVEMENT)
- Focus on missing required checks first
- Add quality checks incrementally
- Target 95%+ score for production readiness

### For Not Ready Packages ($NOT_READY)
- Address all required checks immediately
- Add missing critical files (package.toml, README.md, license, source)
- Work towards 80%+ score first, then 95%+

## Next Steps

1. **Review** validation results for each package
2. **Fix** failing required checks
3. **Improve** quality checks incrementally
4. **Re-run** validation: \`cargo make marketplace-validate\`
5. **Update** flags: \`cargo make marketplace-validate-update\`

---
**Report generated by**: ggen marketplace validation system
**For questions**: See marketplace/README.md

EOF

    success "Markdown report saved: $REPORT_MD"
else
    # Fallback: simple report without jq
    cat > "$REPORT_MD" <<EOF
# Marketplace Production Validation Report

**Generated**: $(date -u +"%Y-%m-%d %H:%M:%S UTC")

## Validation Results

Validation output saved to: \`validation_results.json\`

To view detailed results, install \`jq\` and run:
\`\`\`bash
jq . validation_results.json
\`\`\`

Or use the ggen CLI:
\`\`\`bash
ggen marketplace validate --json
\`\`\`

---
**Report generated by**: ggen marketplace validation system
EOF
    warn "jq not available. Generated basic report. Install jq for detailed reports."
fi

success "Reports generated successfully!"
log "Markdown: $REPORT_MD"
log "JSON: $REPORT_JSON"

exit 0



