#!/usr/bin/env python3
"""
Test runner for Behavioural Contracts Phase 1 enhancements.

This script runs all Phase 1 tests and provides a summary report.
"""

import subprocess
import sys
from pathlib import Path


def run_command(cmd, description):
    """Run a command and capture its output."""
    print(f"\n{'=' * 60}")
    print(f"🧪 {description}")
    print("=" * 60)

    try:
        result = subprocess.run(
            cmd, shell=True, capture_output=True, text=True, cwd=Path(__file__).parent
        )

        if result.returncode == 0:
            print("✅ PASSED")
            # Print last few lines of output for summary
            lines = result.stdout.strip().split("\n")
            for line in lines[-5:]:
                if "passed" in line or "failed" in line or "coverage" in line:
                    print(line)
        else:
            print("❌ FAILED")
            print(result.stdout)
            print(result.stderr)
            return False

    except Exception as e:
        print(f"❌ ERROR: {e}")
        return False

    return True


def main():
    """Run all Phase 1 tests."""
    print("🚀 BEHAVIOURAL CONTRACTS - PHASE 1 TEST SUITE")
    print("Testing enhanced security features, compliance templates, and hallucination fixes")

    # List of tests to run
    tests = [
        ("ruff check .", "Code Linting (Ruff)"),
        ("ruff format --check .", "Code Formatting Check (Ruff)"),
        ("python -m pytest tests/test_phase1_enhancements.py -v", "Phase 1 Security Enhancements"),
        (
            "python -m pytest tests/test_compliance_templates.py -v",
            "Compliance Templates (GDPR, HIPAA, SOC2, etc.)",
        ),
        (
            "python -m pytest tests/test_github_hallucination_fix.py -v",
            "GitHub Log Agent Hallucination Fix",
        ),
        ("python -m pytest tests/test_simple_contract.py -v", "Basic Contract Functionality"),
    ]

    results = []

    # Run each test suite
    for cmd, description in tests:
        success = run_command(cmd, description)
        results.append((description, success))

    # Summary report
    print(f"\n{'=' * 60}")
    print("📊 TEST SUMMARY REPORT")
    print("=" * 60)

    passed = 0
    total = len(results)

    for description, success in results:
        status = "✅ PASSED" if success else "❌ FAILED"
        print(f"{status} - {description}")
        if success:
            passed += 1

    print(f"\n🎯 OVERALL RESULT: {passed}/{total} test suites passed")

    if passed == total:
        print("\n🎉 ALL TESTS PASSED!")
        print("Phase 1 BCE enhancements are working correctly:")
        print("✅ Prompt injection detection")
        print("✅ Context-aware validation")
        print("✅ Enhanced BCE rules")
        print("✅ Compliance templates")
        print("✅ GitHub hallucination fix")
        print("\n💡 Try the interactive demo: python interactive_demo.py")
        return 0
    else:
        print(f"\n⚠️  {total - passed} test suite(s) failed")
        print("Please check the output above for details.")
        return 1


if __name__ == "__main__":
    sys.exit(main())
