from pathlib import Path

from auraindex.pipeline import ScanConfig, run_scan


def test_pipeline_runs_end_to_end_on_sample_project(tmp_path: Path) -> None:
    sample = tmp_path / "query.sql"
    sample.write_text(
        """
SELECT id
FROM users
WHERE status = 'active'
ORDER BY created_at DESC;
""".strip(),
        encoding="utf-8",
    )

    config = ScanConfig(
        target_path=tmp_path,
        dialect="postgres",
        min_support=1,
        max_indexes_per_table=3,
        extensions={".sql"},
    )
    result = run_scan(config)

    assert result.scanned_files
    assert result.candidates
    assert result.parsed_queries
    assert result.suggestions
    assert "impact" in result.suggestions[0].metadata
    assert "index_type" in result.suggestions[0].metadata
    assert "query_advisories" in result.metadata


def test_pipeline_uses_python_ast_fallback_when_wasm_unavailable(tmp_path: Path, monkeypatch) -> None:
    for index in range(1, 4):
        sample = tmp_path / f"service_{index}.py"
        sample.write_text(
            f"""
def fetch_{index}(conn, email):
    return conn.execute("SELECT id FROM users WHERE email = %s", (email,))
""".strip(),
            encoding="utf-8",
        )

    monkeypatch.setattr(
        "auraindex.extractors.wasm_tree_sitter.WasmTreeSitterExtractor._detect_unavailable_reason",
        lambda self: (
            "WASM extraction requires local tree-sitter-* grammar packages in node_modules. "
            "Run: npm install web-tree-sitter tree-sitter-python tree-sitter-javascript tree-sitter-typescript tree-sitter-php."
        ),
    )

    config = ScanConfig(
        target_path=tmp_path,
        dialect="postgres",
        min_support=1,
        max_indexes_per_table=3,
        extensions={".py"},
    )
    result = run_scan(config)

    assert len(result.candidates) >= 3
    assert result.parsed_queries
    assert not any("WASM extraction requires local tree-sitter" in warning for warning in result.warnings)
    extraction_meta = result.metadata.get("extraction", {})
    assert extraction_meta.get("python_ast_fallback_files") == 3
    assert extraction_meta.get("text_fallback_files") == 0


def test_pipeline_uses_text_fallback_for_php_when_wasm_unavailable(tmp_path: Path, monkeypatch) -> None:
    sample = tmp_path / "anime_controller.php"
    sample.write_text(
        """
<?php
$rows = DB::table('episodes')
  ->where('show_id', $showId)
  ->orderBy('created_at', 'desc')
  ->get();
""".strip(),
        encoding="utf-8",
    )

    monkeypatch.setattr(
        "auraindex.extractors.wasm_tree_sitter.WasmTreeSitterExtractor._detect_unavailable_reason",
        lambda self: (
            "WASM extraction requires local tree-sitter-* grammar packages in node_modules. "
            "Run: npm install web-tree-sitter tree-sitter-python tree-sitter-javascript tree-sitter-typescript tree-sitter-php."
        ),
    )

    config = ScanConfig(
        target_path=tmp_path,
        dialect="mysql",
        min_support=1,
        max_indexes_per_table=3,
        extensions={".php"},
    )
    result = run_scan(config)

    assert result.candidates
    assert result.parsed_queries
    assert not any("WASM extraction requires local tree-sitter" in warning for warning in result.warnings)
    extraction_meta = result.metadata.get("extraction", {})
    assert extraction_meta.get("text_fallback_files") == 1
    assert extraction_meta.get("skipped_non_sql_source_files") == 0
