"""Tests for system auto-discovery."""

import yaml
from pathlib import Path

import pytest

from supermemory.discover import discover_systems
from supermemory.init import init_project


@pytest.fixture
def project_with_modules(tmp_path):
    """Create a project with discoverable Python modules."""
    # Initialize .memory
    root = init_project(project="test", base=tmp_path)

    # Create Python modules
    src = tmp_path / "src"
    for mod in ["auth", "billing", "api"]:
        mod_dir = src / mod
        mod_dir.mkdir(parents=True)
        (mod_dir / "__init__.py").write_text("")
        (mod_dir / "main.py").write_text(f"# {mod} main")

    return tmp_path, root


@pytest.fixture
def project_with_ts_modules(tmp_path):
    """Create a project with TypeScript modules."""
    root = init_project(project="test", base=tmp_path)

    src = tmp_path / "src"
    for mod in ["components", "utils"]:
        mod_dir = src / mod
        mod_dir.mkdir(parents=True)
        (mod_dir / "index.ts").write_text(f"// {mod}")

    return tmp_path, root


def test_discover_python_modules(project_with_modules):
    base, root = project_with_modules

    found = discover_systems(root, base)

    assert set(found) == {"auth", "billing", "api"}

    for name in found:
        doc = root / "systems" / f"{name}.md"
        assert doc.exists()
        content = doc.read_text()
        assert name in content


def test_discover_typescript_modules(project_with_ts_modules):
    base, root = project_with_ts_modules

    found = discover_systems(root, base)
    assert set(found) == {"components", "utils"}


def test_discover_skips_existing(project_with_modules):
    base, root = project_with_modules

    # Create an existing doc
    (root / "systems" / "auth.md").write_text("# Existing auth doc")

    found = discover_systems(root, base)

    # auth should not be in found (already existed)
    assert "auth" not in found
    # But billing and api should be
    assert "billing" in found
    assert "api" in found

    # Existing doc should be unchanged
    assert "Existing auth doc" in (root / "systems" / "auth.md").read_text()


def test_discover_respects_ignore(tmp_path):
    root = init_project(project="test", base=tmp_path)

    # Create a module inside node_modules (should be ignored)
    nm = tmp_path / "src" / "node_modules" / "pkg"
    nm.mkdir(parents=True)
    (nm / "index.ts").write_text("")

    found = discover_systems(root, tmp_path)
    assert "pkg" not in found


def test_discover_empty_project(tmp_path):
    root = init_project(project="test", base=tmp_path)

    found = discover_systems(root, tmp_path)
    assert found == []
