"""System auto-discovery — scans codebase for module boundaries."""

from __future__ import annotations

from pathlib import Path

import yaml

from supermemory.config import load_config


# Files that indicate a module boundary
MODULE_MARKERS = {
    "__init__.py",   # Python
    "index.ts",      # TypeScript
    "index.js",      # JavaScript
    "mod.rs",        # Rust
    "main.go",       # Go (package-level)
    "go.mod",        # Go (module root)
}

DEFAULT_IGNORE = {"node_modules", "__pycache__", ".venv", ".git", ".memory", "venv", "dist", "build"}


def discover_systems(root: Path, base: Path | None = None) -> list[str]:
    """Scan codebase for modules and create skeleton system docs.

    Returns list of discovered system names.
    """
    base = base or root.parent
    config = load_config(root)

    sys_config = config.get("systems", {})
    discover_paths = sys_config.get("discover_paths", ["src/"])
    max_depth = sys_config.get("discover_depth", 3)
    ignore = set(sys_config.get("ignore", [])) | DEFAULT_IGNORE

    discovered: list[str] = []

    for search_path in discover_paths:
        search_root = base / search_path
        if not search_root.is_dir():
            continue
        _scan_dir(search_root, base, root, max_depth, ignore, discovered, depth=0)

    return discovered


def _scan_dir(
    directory: Path,
    base: Path,
    root: Path,
    max_depth: int,
    ignore: set[str],
    discovered: list[str],
    depth: int,
) -> None:
    """Recursively scan for module boundaries."""
    if depth > max_depth:
        return

    try:
        entries = sorted(directory.iterdir())
    except PermissionError:
        return

    has_marker = any((directory / m).exists() for m in MODULE_MARKERS)

    if has_marker and depth > 0:
        system_name = directory.name
        doc_path = root / "systems" / f"{system_name}.md"
        if not doc_path.exists():
            _create_system_doc(system_name, directory, base, root)
            discovered.append(system_name)

    for entry in entries:
        if entry.is_dir() and entry.name not in ignore and not entry.name.startswith("."):
            _scan_dir(entry, base, root, max_depth, ignore, discovered, depth + 1)


def _create_system_doc(name: str, module_path: Path, base: Path, root: Path) -> None:
    """Create a skeleton system doc if one doesn't already exist."""
    doc_path = root / "systems" / f"{name}.md"
    if doc_path.exists():
        return

    rel_path = module_path.relative_to(base)
    key_files = _find_key_files(module_path)

    content = f"""---
owner:
last_verified:
paths:
  - "{rel_path}"
tags:
  - {name}
---

# {name}

## Purpose

Auto-discovered module at `{rel_path}`. Describe what this system does.

## Architecture

Key patterns, data flow, abstractions.

## Key Files

"""
    for kf in key_files[:10]:
        rel = kf.relative_to(base)
        content += f"- `{rel}`\n"

    content += """
## Integration Points

How this system connects to other systems.

## Configuration

Environment variables, config files, feature flags.

## Known Gotchas

Link to relevant gotcha docs.
"""
    doc_path.write_text(content)


def _find_key_files(module_path: Path) -> list[Path]:
    """Find important files in a module directory."""
    key_files = []
    for f in sorted(module_path.rglob("*")):
        if f.is_file() and not f.name.startswith(".") and f.suffix in {
            ".py", ".ts", ".js", ".rs", ".go", ".java", ".rb",
        }:
            key_files.append(f)
    return key_files
