"""Lecture 02 lab checker. Run inside your portfolio repo:

    python check_repo.py /path/to/ds1-portfolio
"""
import subprocess
import sys
from pathlib import Path


def git(repo: Path, *args: str) -> str:
    result = subprocess.run(
        ["git", "-C", str(repo), *args], capture_output=True, text=True
    )
    return result.stdout.strip() if result.returncode == 0 else ""


def is_repo(repo: Path) -> bool:
    return git(repo, "rev-parse", "--is-inside-work-tree") == "true"


def commit_count(repo: Path) -> int:
    out = git(repo, "rev-list", "--count", "HEAD")
    return int(out) if out else 0


def ignores(repo: Path, patterns: list[str]) -> bool:
    path = repo / ".gitignore"
    if not path.exists():
        return False
    lines = {line.strip().rstrip("/") for line in path.read_text().splitlines()}
    return all(p.rstrip("/") in lines for p in patterns)


def tracks_venv(repo: Path) -> bool:
    files = git(repo, "ls-files").splitlines()
    return any(f.startswith((".venv/", "venv/")) for f in files)


def has_file(repo: Path, name: str) -> bool:
    return name in git(repo, "ls-files").splitlines()


def branch_merged(repo: Path, branch: str, into: str = "main") -> bool:
    merged = [b.strip(" *") for b in git(repo, "branch", "--merged", into).splitlines()]
    return branch in merged


def has_merge_commit(repo: Path) -> bool:
    return bool(git(repo, "rev-list", "--merges", "-n", "1", "HEAD"))


def has_remote(repo: Path, name: str = "origin") -> bool:
    return name in git(repo, "remote").splitlines()


def run_checks(repo: Path) -> dict[str, bool]:
    if not is_repo(repo):
        return {"is a git repository": False}
    return {
        "is a git repository": True,
        "at least 4 commits": commit_count(repo) >= 4,
        ".gitignore lists .venv and __pycache__": ignores(repo, [".venv", "__pycache__"]),
        ".venv is not committed": not tracks_venv(repo),
        "requirements.txt is committed": has_file(repo, "requirements.txt"),
        "README.md is committed": has_file(repo, "README.md"),
        "feature/readme merged into main": branch_merged(repo, "feature/readme"),
        "a merge commit exists (conflict task)": has_merge_commit(repo),
        "remote origin is set": has_remote(repo),
    }


def main() -> int:
    repo = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve()
    results = run_checks(repo)
    for name, ok in results.items():
        print(f"[{'PASS' if ok else 'FAIL'}] {name}")
    passed = sum(results.values())
    print(f"{passed}/{len(results)} checks passed")
    return 0 if passed == len(results) else 1


if __name__ == "__main__":
    sys.exit(main())
