"""Builds a model solution repo and checks that every lab check passes.

Run: pytest test_check_repo.py
"""
import subprocess
from pathlib import Path

import pytest

from check_repo import run_checks


def sh(repo: Path, *args: str) -> None:
    subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True)


def write(repo: Path, name: str, text: str) -> None:
    (repo / name).parent.mkdir(parents=True, exist_ok=True)
    (repo / name).write_text(text)


@pytest.fixture
def solution_repo(tmp_path: Path) -> Path:
    repo = tmp_path / "ds1-portfolio"
    repo.mkdir()
    sh(repo, "init", "-b", "main")
    sh(repo, "config", "user.name", "Learner")
    sh(repo, "config", "user.email", "learner@example.com")
    write(repo, ".venv/bin/python", "")
    write(repo, ".gitignore", ".venv/\n__pycache__/\n")
    write(repo, "requirements.txt", "numpy>=1.26\n")
    sh(repo, "add", ".")
    sh(repo, "commit", "-m", "Add environment files")
    write(repo, "README.md", "# DS1 portfolio\n")
    sh(repo, "add", "README.md")
    sh(repo, "commit", "-m", "Add README")
    sh(repo, "switch", "-c", "feature/readme")
    write(repo, "README.md", "# DS1 portfolio\n\nLabs from the DS1 path.\n")
    sh(repo, "commit", "-am", "Describe the repo")
    sh(repo, "switch", "main")
    write(repo, "README.md", "# DS1 portfolio\n\nWork for group AI-2.\n")
    sh(repo, "commit", "-am", "Name the group")
    subprocess.run(["git", "-C", str(repo), "merge", "feature/readme"], capture_output=True)
    write(repo, "README.md", "# DS1 portfolio\n\nLabs from the DS1 path, group AI-2.\n")
    sh(repo, "commit", "-am", "Merge feature/readme, resolve README conflict")
    sh(repo, "remote", "add", "origin", "https://example.com/learner/ds1-portfolio.git")
    return repo


def test_solution_passes_all_checks(solution_repo: Path):
    results = run_checks(solution_repo)
    assert all(results.values()), [k for k, v in results.items() if not v]


def test_committed_venv_fails(solution_repo: Path):
    sh(solution_repo, "add", "-f", ".venv/bin/python")
    sh(solution_repo, "commit", "-m", "Oops")
    assert run_checks(solution_repo)[".venv is not committed"] is False


def test_empty_folder_is_not_a_repo(tmp_path: Path):
    assert run_checks(tmp_path) == {"is a git repository": False}
