from pathlib import Path

import pytest

from auraindex.cli import main


def test_cli_writes_reports_to_requested_directory(tmp_path: Path, monkeypatch) -> None:
    project_dir = tmp_path / "project"
    project_dir.mkdir(parents=True, exist_ok=True)
    (project_dir / "query.sql").write_text(
        """
SELECT id
FROM users
WHERE status = 'active'
ORDER BY created_at DESC;
""".strip(),
        encoding="utf-8",
    )
    output_dir = tmp_path / "reports"
    monkeypatch.setattr("auraindex.cli.webbrowser.open", lambda *args, **kwargs: True)

    exit_code = main(
        [
            "--path",
            str(project_dir),
            "--extensions",
            ".sql",
            "--min-support",
            "1",
            "--report-dir",
            str(output_dir),
            "--show-top",
            "--limit-suggestions",
            "5",
        ]
    )

    assert exit_code == 0
    assert (output_dir / "auraindex_report.json").exists()
    assert (output_dir / "auraindex_indexes.sql").exists()
    assert (output_dir / "auraindex_migration.sql").exists()
    assert (output_dir / "auraindex_orm_snippets.md").exists()
    assert (output_dir / "auraindex_report.md").exists()
    assert (output_dir / "auraindex_report.html").exists()


def test_cli_help_groups_and_limit_flag(capsys) -> None:
    with pytest.raises(SystemExit) as exc:
        main(["--help"])

    assert exc.value.code == 0
    help_text = capsys.readouterr().out
    assert "Scan target and extraction" in help_text
    assert "Report output files" in help_text
    assert "Recommendation behavior" in help_text
    assert "Live database introspection" in help_text
    assert "EXPLAIN validation" in help_text
    assert "Display and exit behavior" in help_text
    assert "--limit-suggestions" in help_text
    assert "--top-suggestions" not in help_text
