#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
=============================================================================
KIEU STORY - MASTER E2E TEST RUNNER & COVERAGE AGGREGATOR
=============================================================================
Runs all test suites across Tiers 1-4, aggregating coverage for Features F1-F13.
Produces structured console output and summary diagnostics.
=============================================================================
"""

import os
import sys
import time
import argparse
import unittest
from pathlib import Path

# Set UTF-8 encoding on Windows console
if sys.platform == "win32":
    try:
        sys.stdout.reconfigure(encoding="utf-8")
        sys.stderr.reconfigure(encoding="utf-8")
    except Exception:
        pass

TESTS_DIR = Path(__file__).resolve().parent
BASE_DIR = TESTS_DIR.parent
if str(BASE_DIR) not in sys.path:
    sys.path.insert(0, str(BASE_DIR))
if str(TESTS_DIR) not in sys.path:
    sys.path.insert(0, str(TESTS_DIR))


def run_test_suite(tier_filter: int = None, feature_filter: str = None, verbose: bool = False):
    loader = unittest.TestLoader()
    suite = unittest.TestSuite()

    tier_files = {
        1: ("Tier 1: Feature Coverage (F1-F13)", "test_tier1_features.py"),
        2: ("Tier 2: Boundary & Corner Cases (F1-F13)", "test_tier2_boundaries.py"),
        3: ("Tier 3: Cross-Feature Interactions", "test_tier3_interactions.py"),
        4: ("Tier 4: Real-World Application Workloads", "test_tier4_workloads.py")
    }

    selected_tiers = [tier_filter] if tier_filter in tier_files else [1, 2, 3, 4]

    tier_suites = {}
    for t in selected_tiers:
        label, filename = tier_files[t]
        file_path = TESTS_DIR / filename
        if file_path.exists():
            mod_name = filename[:-3]
            s = loader.loadTestsFromName(mod_name)
            tier_suites[t] = (label, s)
            suite.addTests(s)

    print("=" * 80)
    print("🎬 KIEU STORY AI CINEMA — COMPREHENSIVE E2E TEST SUITE RUNNER")
    print(f"   Target: Features F1-F13 across Tiers 1-4 | Total Test Cases: {suite.countTestCases()}")
    print("=" * 80)

    start_time = time.time()
    runner = unittest.TextTestRunner(verbosity=2 if verbose else 1)
    result = runner.run(suite)
    elapsed = time.time() - start_time

    total = result.testsRun
    failures = len(result.failures)
    errors = len(result.errors)
    passed = total - failures - errors

    print("\n" + "=" * 80)
    print("📊 MASTER TEST EXECUTION SUMMARY REPORT")
    print("=" * 80)
    print(f"Total Tests Executed:  {total}")
    print(f"  ✓ Passed:            {passed} ({passed / total * 100:.1f}%)" if total else "  ✓ Passed: 0")
    print(f"  ✗ Failures:          {failures}")
    print(f"  💥 Errors:            {errors}")
    print(f"Execution Duration:    {elapsed:.2f} seconds")
    print("=" * 80)

    if failures > 0 or errors > 0:
        print("\n🔍 DETECTED IMPLEMENTATION GAPS / ESCALATED DEFECTS:")
        print("-" * 80)
        all_issues = result.failures + result.errors
        for idx, (test, traceback_str) in enumerate(all_issues, 1):
            test_id = test.id().split(".")[-1]
            short_reason = traceback_str.strip().splitlines()[-1]
            print(f"[{idx:02d}] {test_id}")
            print(f"     Reason: {short_reason}")
        print("-" * 80)
    else:
        print("\n🎉 ALL TESTS PASSED! 100% SPECIFICATION ADHERENCE VERIFIED.")

    return result


def main():
    parser = argparse.ArgumentParser(description="KieuStory Master E2E Test Runner")
    parser.add_argument("--tier", type=int, choices=[1, 2, 3, 4], default=None, help="Run only specific test tier")
    parser.add_argument("--feature", type=str, default=None, help="Filter tests by feature ID (e.g. F1, F2)")
    parser.add_argument("-v", "--verbose", action="store_true", help="Verbose test execution output")

    args = parser.parse_args()
    result = run_test_suite(tier_filter=args.tier, feature_filter=args.feature, verbose=args.verbose)
    sys.exit(0 if result.wasSuccessful() else 1)


if __name__ == "__main__":
    main()
