#!/usr/bin/env python3
"""
Sentimatrix Test Runner

Runs all unit tests and generates reports.

Usage:
    python run_tests.py              # Run all tests
    python run_tests.py --unit       # Run only unit tests
    python run_tests.py --coverage   # Run with coverage report
    python run_tests.py --verbose    # Run with verbose output
"""

import argparse
import subprocess
import sys
from datetime import datetime
from pathlib import Path


def run_tests(args):
    """Run pytest with specified options."""
    project_root = Path(__file__).parent
    tests_dir = project_root / "tests"
    results_dir = tests_dir / "results"
    results_dir.mkdir(exist_ok=True)

    # Base pytest command
    cmd = ["python", "-m", "pytest"]

    # Add test directory
    if args.unit:
        cmd.append(str(tests_dir / "unit"))
    elif args.integration:
        cmd.append(str(tests_dir / "integration"))
    else:
        cmd.append(str(tests_dir))

    # Verbose output
    if args.verbose:
        cmd.append("-v")

    # Coverage options
    if args.coverage:
        cmd.extend([
            "--cov=sentimatrix",
            "--cov-report=term-missing",
            f"--cov-report=html:{results_dir}/coverage_html",
        ])

    # Generate JUnit XML report
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    cmd.append(f"--junitxml={results_dir}/test_results_{timestamp}.xml")

    # Markers
    if args.skip_slow:
        cmd.append("-m not slow")

    if args.skip_live:
        cmd.append("-m not live")

    # Print command
    print(f"Running: {' '.join(cmd)}")
    print("-" * 60)

    # Run tests
    result = subprocess.run(cmd, cwd=project_root)

    # Generate summary report
    generate_summary_report(results_dir, timestamp, result.returncode)

    return result.returncode


def generate_summary_report(results_dir: Path, timestamp: str, return_code: int):
    """Generate a summary report of test results."""
    report_file = results_dir / f"test_summary_{timestamp}.md"

    status = "PASSED" if return_code == 0 else "FAILED"

    report_content = f"""# Sentimatrix Test Summary

**Date:** {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
**Status:** {status}
**Return Code:** {return_code}

## Test Configuration

- Python Version: {sys.version}
- Test Framework: pytest

## Results

See `test_results_{timestamp}.xml` for detailed JUnit XML results.

## Coverage

If coverage was enabled, see `coverage_html/index.html` for detailed coverage report.

---
*Generated by Sentimatrix Test Runner*
"""

    report_file.write_text(report_content)
    print(f"\nSummary report written to: {report_file}")


def main():
    parser = argparse.ArgumentParser(
        description="Sentimatrix Test Runner",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )

    parser.add_argument(
        "--unit",
        action="store_true",
        help="Run only unit tests",
    )
    parser.add_argument(
        "--integration",
        action="store_true",
        help="Run only integration tests",
    )
    parser.add_argument(
        "--coverage",
        action="store_true",
        help="Run with coverage report",
    )
    parser.add_argument(
        "--verbose", "-v",
        action="store_true",
        help="Verbose output",
    )
    parser.add_argument(
        "--skip-slow",
        action="store_true",
        help="Skip slow tests",
    )
    parser.add_argument(
        "--skip-live",
        action="store_true",
        help="Skip tests requiring live API access",
    )

    args = parser.parse_args()

    sys.exit(run_tests(args))


if __name__ == "__main__":
    main()
