"""Run all domain app test modules without moving them into a shared tests folder."""

from __future__ import annotations

from argparse import ArgumentParser
from pathlib import Path
from typing import Iterable, Sequence

PACKAGE_DIR = Path(__file__).resolve().parent


def collect_test_files(targets: Iterable[str] | None = None) -> list[str]:
    if targets is None:
        paths = sorted(path for path in PACKAGE_DIR.glob("*/tests.py") if path.is_file())
        return [str(path) for path in paths]

    paths: list[str] = []
    for target in targets:
        candidate = Path(target)
        if candidate.is_file():
            paths.append(str(candidate.resolve()))
            continue

        resolved = PACKAGE_DIR / target / "tests.py"
        if resolved.is_file():
            paths.append(str(resolved))
            continue

        raise FileNotFoundError(f"no domain test module found for {target!r}")

    return list(dict.fromkeys(paths))


def build_parser() -> ArgumentParser:
    parser = ArgumentParser(description="Run domain app test modules.")
    parser.add_argument(
        "targets",
        nargs="*",
        help="Optional app names or explicit tests.py paths. If omitted, all domain app tests are run.",
    )
    return parser


def main(argv: Sequence[str] | None = None) -> int:
    parser = build_parser()
    args, pytest_args = parser.parse_known_args(argv)

    test_files = collect_test_files(args.targets or None)
    if not test_files:
        raise SystemExit("no domain tests found")

    import pytest

    return pytest.main([*test_files, *pytest_args])


if __name__ == "__main__":
    raise SystemExit(main())
