"""Framework auto-detection for migrate_framework."""
from __future__ import annotations
import json
from pathlib import Path


def detect_framework(source_dir: str) -> dict:
    """
    Detect the Playwright framework type from a source directory.

    Returns:
        {
            framework: "playwright-bdd-ts" | "playwright-bdd-js" |
                       "playwright-ts"     | "playwright-js",
            language: "typescript" | "javascript",
            bdd: bool,
            config_files: list[str],
            file_counts: { ts: int, js: int, feature: int },
        }
    """
    root = Path(source_dir)
    if not root.exists():
        return {"error": f"Source directory does not exist: {source_dir}"}

    _skip = {"node_modules", "dist", ".venv", "__pycache__", ".git"}

    def _walk(suffix: str) -> list[Path]:
        return [
            p for p in root.rglob(f"*{suffix}")
            if not any(s in p.parts for s in _skip)
        ]

    ts_files      = _walk(".ts")
    js_files      = _walk(".js")
    feature_files = _walk(".feature")

    file_counts = {
        "ts": len(ts_files),
        "js": len(js_files),
        "feature": len(feature_files),
    }

    language = "typescript" if len(ts_files) >= len(js_files) else "javascript"
    bdd = len(feature_files) > 0

    # Confirm BDD via package.json deps
    pkg_path = root / "package.json"
    if pkg_path.exists():
        try:
            pkg  = json.loads(pkg_path.read_text(encoding="utf-8"))
            deps = {**pkg.get("dependencies", {}), **pkg.get("devDependencies", {})}
            if "@cucumber/cucumber" in deps or "cucumber" in deps:
                bdd = True
        except Exception:
            pass

    config_files = []
    for name in (
        "playwright.config.ts", "playwright.config.js",
        "cucumber.js", "cucumber.cjs", "cucumber.mjs",
        "tsconfig.json", "package.json",
    ):
        if (root / name).exists():
            config_files.append(name)

    if bdd and language == "typescript":
        framework = "playwright-bdd-ts"
    elif bdd:
        framework = "playwright-bdd-js"
    elif language == "typescript":
        framework = "playwright-ts"
    else:
        framework = "playwright-js"

    return {
        "framework": framework,
        "language": language,
        "bdd": bdd,
        "config_files": config_files,
        "file_counts": file_counts,
    }
