#!/usr/bin/env python3
"""Generate markdown test report from test output."""

import os
import re
from datetime import datetime


def generate_report():
    """Generate markdown report from test_output.txt."""

    # Read test output
    try:
        with open("test_output.txt", "r") as f:
            test_output = f.read()
    except FileNotFoundError:
        test_output = "❌ No test output found"

    # Extract key metrics
    success_rate = "Unknown"
    total_tests = "Unknown"
    passed_tests = "Unknown"
    failed_tests = "Unknown"
    duration = "Unknown"

    if match := re.search(r"Total Tests: (\d+)", test_output):
        total_tests = match.group(1)

    if match := re.search(r"✓ Passed: (\d+)", test_output):
        passed_tests = match.group(1)

    if match := re.search(r"✗ Failed: (\d+)", test_output):
        failed_tests = match.group(1)

    if match := re.search(r"Success Rate: ([\d.]+)%", test_output):
        success_rate = f"{match.group(1)}%"

    if match := re.search(r"Total Duration: ([\d.]+)ms", test_output):
        duration_ms = float(match.group(1))
        duration = f"{duration_ms / 1000:.2f}s"

    # Determine status
    status = "✅ ALL TESTS PASSED" if "Success Rate: 100" in test_output else "❌ SOME TESTS FAILED"

    # Get GitHub context from environment
    commit = os.getenv("GITHUB_SHA", "unknown")[:7]
    branch = os.getenv("GITHUB_REF_NAME", "unknown")
    event = os.getenv("GITHUB_EVENT_NAME", "unknown")
    run_id = os.getenv("GITHUB_RUN_ID", "")
    repo = os.getenv("GITHUB_REPOSITORY", "")
    server_url = os.getenv("GITHUB_SERVER_URL", "https://github.com")

    # Build report with comprehensive output (always visible for PR comments)
    report = f"""# 🧪 Test Results

**Status**: {status}
**Time**: {datetime.now().strftime("%Y-%m-%d %H:%M:%S UTC")}
**Commit**: `{commit}`
**Branch**: `{branch}`

## 📊 Summary

| Metric | Value |
|--------|-------|
| Total Tests | {total_tests} |
| Passed | {passed_tests} |
| Failed | {failed_tests} |
| Success Rate | {success_rate} |
| Duration | {duration} |

## 📝 Comprehensive Test Output

```
{test_output}
```

---

**Workflow**: [{event}]({server_url}/{repo}/actions/runs/{run_id})
**Commit**: [{commit}]({server_url}/{repo}/commit/{os.getenv("GITHUB_SHA", "")})

*Generated by GitHub Actions*
"""

    # Write report
    with open("test_report.md", "w") as f:
        f.write(report)

    print("✅ Report generated: test_report.md")


if __name__ == "__main__":
    generate_report()
