"""
Playwright Test Executor

Executes Playwright E2E tests.
"""

import os
import re
import json
import subprocess
from pathlib import Path
from typing import Dict

from ..config import get_running_tests


async def run_playwright_tests(base_path: Path, service_id: str = "") -> Dict:
    """Fuehrt Playwright E2E-Tests aus"""
    running_tests = get_running_tests()

    if not base_path.exists():
        return {"passed": 0, "failed": 0, "total": 0, "output": f"Pfad existiert nicht: {base_path}", "failed_test_ids": []}

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

    try:
        env = os.environ.copy()
        env["CI"] = "true"

        result = subprocess.run(
            ["npx", "playwright", "test", "--reporter=json"],
            cwd=str(base_path),
            capture_output=True,
            text=True,
            timeout=600,  # E2E Tests brauchen laenger
            env=env,
        )

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

        # Parse Playwright JSON Output
        try:
            pw_result = json.loads(output)
            for suite in pw_result.get("suites", []):
                for spec in suite.get("specs", []):
                    for test in spec.get("tests", []):
                        for result_item in test.get("results", []):
                            if result_item.get("status") == "passed":
                                passed += 1
                            elif result_item.get("status") == "failed":
                                failed += 1
                                failed_test_ids.append({
                                    "id": spec.get("title", ""),
                                    "name": spec.get("title", ""),
                                    "file_path": spec.get("file", ""),
                                    "error_message": result_item.get("error", {}).get("message", "")[:500],
                                    "error_type": "e2e",
                                    "suggestion": "Pruefe den E2E-Test und die Anwendung",
                                })
        except json.JSONDecodeError:
            # Fallback: Parse Text-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))

        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": passed + failed,
            "output": output[:5000],
            "failed_test_ids": failed_test_ids,
        }
    except subprocess.TimeoutExpired:
        return {"passed": 0, "failed": 0, "total": 0, "output": "Timeout nach 10 Minuten", "failed_test_ids": []}
    except Exception as e:
        return {"passed": 0, "failed": 0, "total": 0, "output": str(e), "failed_test_ids": []}
