#!/usr/bin/env python3
"""
Test runner for io_tests module

Runs all unit tests for the io module following GUIDELINES_TEST.md.

Company: eXonware.com
Author: Eng. Muhammad AlShehri
Email: connect@exonware.com
"""

import sys
import pytest
from pathlib import Path
from datetime import datetime


def main():
    """Run io module unit tests."""
    # Add src to Python path
    src_path = Path(__file__).parent.parent.parent.parent / "src"
    sys.path.insert(0, str(src_path))
    
    # Handle Unicode encoding for Windows
    try:
        print("🧩 Unit Tests - IO Module")
        print(f"📂 Test Directory: {Path(__file__).parent}")
    except UnicodeEncodeError:
        print("Unit Tests - IO Module")
        print(f"Test Directory: {Path(__file__).parent}")
    print("="*80)
    
    # Run unit tests for io module
    exit_code = pytest.main([
        "-v",
        "--tb=short",
        "-x",  # Stop on first failure
        str(Path(__file__).parent),
        "-m", "xsystem_unit"
    ])
    
    # Status output
    if exit_code == 0:
        status_emoji = "IO unit tests PASSED"
        status_plain = "IO unit tests PASSED"
    else:
        status_emoji = "IO unit tests FAILED"  
        status_plain = "IO unit tests FAILED"
    
    try:
        print(f"\n✅ {status_emoji}" if exit_code == 0 else f"\n❌ {status_emoji}")
    except UnicodeEncodeError:
        print(f"\n{status_plain}")
    
    # Save Markdown output
    output_file = Path(__file__).parent / "runner_out.md"
    markdown_content = f"""# IO Module Unit Test Results

**Module:** io_tests
**Layer:** 1.unit
**Generated:** {datetime.now().strftime("%d-%b-%Y %H:%M:%S")}
**Status:** {'PASSED' if exit_code == 0 else 'FAILED'}

---

## Test Structure

Following GUIDELINES_TEST.md structure, mirroring io module organization:

- `test_contracts.py` - IO interfaces and enums
- `test_facade.py` - XWIO facade
- `codec_tests/` - Codec foundation tests
- `serialization_tests/` - Serialization tests
  - `formats_tests/` - Format-specific tests
    - `text_tests/` - JSON, YAML, TOML, etc.
    - `binary_tests/` - MessagePack, Pickle, etc.
    - `schema_tests/` - Protobuf, Avro, etc.
    - `scientific_tests/` - HDF5, Feather, etc.
    - `database_tests/` - SQLite, LMDB, etc.
- `archive_tests/` - Archive and compression tests
- `common_tests/` - Common utilities tests
- `file_tests/` - File operations tests
- `folder_tests/` - Folder operations tests
- `stream_tests/` - Stream operations tests

---

## Test Execution

**Command:** `python tests/1.unit/io_tests/runner.py`

**Markers:** `xsystem_unit`

**Options:**
- Verbose output (`-v`)
- Short traceback (`--tb=short`)
- Stop on first failure (`-x`)

---

## Result

{'✅ PASSED' if exit_code == 0 else '❌ FAILED'}

**Exit Code:** {exit_code}

---

*Generated by eXonware test runner - Excellence Edition*
"""
    
    output_file.write_text(markdown_content, encoding='utf-8')
    try:
        print(f"\n📝 Results saved to: {output_file}")
    except UnicodeEncodeError:
        print(f"\nResults saved to: {output_file}")
    
    sys.exit(exit_code)


if __name__ == "__main__":
    main()

