#!/usr/bin/env python3
#exonware/xwsyntax/tests/1.unit/runner.py
"""
Unit test orchestrator for xwsyntax
Calls all module test runners with Markdown output.
Company: eXonware.com
Author: eXonware Backend Team
Email: connect@exonware.com
Version: 0.0.1
Generation Date: 29-Oct-2025
"""

import sys
import subprocess
from pathlib import Path
from datetime import datetime
# ⚠️ CRITICAL: Configure UTF-8 encoding for Windows console using xwsystem utility
from exonware.xwsystem.console.cli import ensure_utf8_console
ensure_utf8_console()


def main():
    """Unit test orchestrator - calls all module runners."""
    # Add src to Python path
    src_path = Path(__file__).parent.parent.parent / "src"
    sys.path.insert(0, str(src_path))
    print("🧩 Unit Tests - Module by Module")
    unit_dir = Path(__file__).parent
    exit_codes = []
    module_results = []
    # Find all module runners
    for module_dir in sorted(unit_dir.iterdir()):
        if module_dir.is_dir() and not module_dir.name.startswith('__') and module_dir.name.endswith('_tests'):
            runner = module_dir / "runner.py"
            if runner.exists():
                print(f"\n📦 Testing module: {module_dir.name}")
                result = subprocess.run([sys.executable, str(runner)])
                exit_codes.append(result.returncode)
                status = "✅ PASSED" if result.returncode == 0 else "❌ FAILED"
                module_results.append((module_dir.name, status, result.returncode))
    # Summary
    if all(code == 0 for code in exit_codes):
        final_status = "✅ All unit tests PASSED"
        print(f"\n{final_status}")
        exit_code = 0
    else:
        final_status = "❌ Some unit tests FAILED"
        print(f"\n{final_status}")
        exit_code = 1
    # Save Markdown output
    output_file = unit_dir / "runner_out.md"
    markdown_content = f"""# Unit Test Results
**Layer:** 1.unit  
**Generated:** {datetime.now().strftime("%d-%b-%Y %H:%M:%S")}  
**Total Modules:** {len(module_results)}  
**Status:** {'PASSED' if exit_code == 0 else 'FAILED'}
---
## Module Test Results
| Module | Status | Exit Code |
|--------|--------|-----------|
"""
    for module_name, status, code in module_results:
        markdown_content += f"| {module_name} | {status} | {code} |\n"
    markdown_content += f"""
---
## Summary
- **Total Modules Tested:** {len(module_results)}
- **Passed:** {sum(1 for _, _, code in module_results if code == 0)}
- **Failed:** {sum(1 for _, _, code in module_results if code != 0)}
### {final_status}
---
*Generated by eXonware test runner - Production Excellence Edition*
"""
    output_file.write_text(markdown_content, encoding='utf-8')
    print(f"\n📝 Results saved to: {output_file}")
    sys.exit(exit_code)
if __name__ == "__main__":
    main()
