from __future__ import annotations

from pathlib import Path

from pyguard.models import PackageInfo, PackageMetadata

IGNORED_DIR_NAMES = {
    ".git",
    ".hg",
    ".mypy_cache",
    ".pytest_cache",
    ".ruff_cache",
    ".venv",
    "build",
    "dist",
    "__pycache__",
    "site-packages",
}


def load_local_package(target: str) -> PackageInfo:
    if "==" in target:
        name, version = target.split("==", maxsplit=1)
        return PackageInfo(name=name, version=version, source_path=Path.cwd())

    target_path = Path(target)
    if target_path.exists():
        source_path = target_path.resolve()
        files: dict[str, str] = {}
        for path in source_path.rglob("*.py"):
            if any(part in IGNORED_DIR_NAMES for part in path.relative_to(source_path).parts):
                continue
            try:
                files[str(path.relative_to(source_path))] = path.read_text(encoding="utf-8")
            except UnicodeDecodeError:
                continue
        return PackageInfo(
            name=source_path.name.lower(),
            version="0.0.0",
            source_path=source_path,
            files=files,
            metadata=PackageMetadata(),
        )

    return PackageInfo(name=target, version="unknown", source_path=Path.cwd())
