import os
import subprocess
from pathlib import Path

import pytest

from project_hub.core.config import Config
from project_hub.core.discovery import discover_repos


def test_discover_finds_git_repos(tmp_workspace: Path) -> None:
    repos = discover_repos(tmp_workspace, Config())
    assert {r.name for r in repos} == {"repo-alpha", "repo-beta", "repo-gamma"}


def test_discover_skips_non_git_dirs(tmp_workspace: Path) -> None:
    (tmp_workspace / "not-a-repo").mkdir()
    repos = discover_repos(tmp_workspace, Config())
    assert "not-a-repo" not in {r.name for r in repos}
    assert len(repos) == 3


def test_discover_respects_include(tmp_workspace: Path) -> None:
    repos = discover_repos(tmp_workspace, Config(include="repo-a*"))
    assert {r.name for r in repos} == {"repo-alpha"}


def test_discover_respects_exclude(tmp_workspace: Path) -> None:
    repos = discover_repos(tmp_workspace, Config(exclude=["repo-gamma"]))
    assert {r.name for r in repos} == {"repo-alpha", "repo-beta"}


def test_discover_parses_remote_url(tmp_workspace: Path) -> None:
    config = Config(forges={"gitlab.com": {"type": "gitlab"}})
    repos = discover_repos(tmp_workspace, config)
    repo = next(r for r in repos if r.name == "repo-alpha")
    assert repo.forge_host == "gitlab.com"
    assert repo.forge_type == "gitlab"
    assert repo.has_forge is True
    assert repo.project_path == "group/repo-alpha"


def test_discover_unknown_forge_host(tmp_workspace: Path) -> None:
    config = Config(forges={})
    repos = discover_repos(tmp_workspace, config)
    assert all(r.has_forge is False for r in repos)


def test_discover_parses_https_remote(tmp_workspace: Path) -> None:
    repo_dir = tmp_workspace / "repo-https"
    repo_dir.mkdir()
    subprocess.run(["git", "init"], cwd=repo_dir, capture_output=True)
    subprocess.run(
        ["git", "remote", "add", "origin", "https://github.com/myorg/myproject.git"],
        cwd=repo_dir,
        capture_output=True,
    )

    config = Config(forges={"github.com": {"type": "github"}})
    repos = discover_repos(tmp_workspace, config)
    repo = next((r for r in repos if r.name == "repo-https"), None)
    assert repo is not None
    assert repo.forge_host == "github.com"
    assert repo.forge_type == "github"
    assert repo.has_forge is True
    assert repo.project_path == "myorg/myproject"
