"""
Container Test Executor

Executes tests inside Docker containers via docker exec.
"""

import re
import asyncio
import subprocess
from typing import Dict

from ..config import get_running_tests


async def run_tests_in_container(
    container_name: str,
    framework: str,
    base_path: str,
    service_id: str,
    pytest_args: str = ""
) -> Dict:
    """Fuehrt Tests in einem anderen Docker-Container aus via docker exec"""
    running_tests = get_running_tests()

    running_tests[service_id] = {
        "current_file": "",
        "files_done": 0,
        "files_total": 1,
        "passed": 0,
        "failed": 0,
        "status": "running"
    }

    try:
        if framework == "pytest":
            cmd = ["docker", "exec", container_name, "python", "-m", "pytest", base_path, "-v", "--tb=short", "-q"]
            # Fuege zusaetzliche pytest Argumente hinzu
            if pytest_args:
                cmd.extend(pytest_args.split())
        else:
            cmd = ["docker", "exec", container_name, "go", "test", "-v", "./..."]

        def run_docker_exec():
            return subprocess.run(cmd, capture_output=True, text=True, timeout=600)

        result = await asyncio.to_thread(run_docker_exec)

        output = result.stdout + result.stderr
        passed = 0
        failed = 0
        failed_test_ids = []

        if framework == "pytest":
            # Parse pytest output
            for line in output.split("\n"):
                if "passed" in line.lower():
                    match = re.search(r"(\d+)\s+passed", line)
                    if match:
                        passed = int(match.group(1))
                if "failed" in line.lower():
                    match = re.search(r"(\d+)\s+failed", line)
                    if match:
                        failed = int(match.group(1))
                if line.startswith("FAILED"):
                    test_name = line.replace("FAILED", "").strip()
                    failed_test_ids.append(test_name)
        else:
            # Parse go test output
            for line in output.split("\n"):
                if line.startswith("--- PASS:"):
                    passed += 1
                elif line.startswith("--- FAIL:"):
                    failed += 1
                    match = re.search(r"--- FAIL: (\S+)", line)
                    if match:
                        failed_test_ids.append(match.group(1))

        total = passed + failed

        running_tests[service_id] = {
            "current_file": "Abgeschlossen",
            "files_done": 1,
            "files_total": 1,
            "passed": passed,
            "failed": failed,
            "status": "completed"
        }

        return {
            "passed": passed,
            "failed": failed,
            "total": total,
            "output": output,
            "failed_test_ids": failed_test_ids
        }

    except Exception as e:
        running_tests[service_id] = {
            "current_file": str(e),
            "files_done": 0,
            "files_total": 1,
            "passed": 0,
            "failed": 0,
            "status": "error"
        }
        return {"passed": 0, "failed": 0, "total": 0, "output": str(e), "failed_test_ids": []}
