from __future__ import annotations

import re
from pathlib import Path

from auraindex.models import QueryCandidate, QueryContext
from auraindex.utils.text import looks_like_sql, normalize_whitespace


def extract_sql_file(file_path: Path) -> list[QueryCandidate]:
    source = file_path.read_text(encoding="utf-8", errors="ignore")
    candidates: list[QueryCandidate] = []

    for statement, start_idx in _split_sql_statements(source):
        cleaned = _sanitize_sql_statement(statement)
        normalized = normalize_whitespace(cleaned)
        if not normalized or not looks_like_sql(normalized):
            continue
        line_number = source.count("\n", 0, start_idx) + 1
        candidates.append(
            QueryCandidate(
                sql=normalized,
                context=QueryContext(
                    file_path=str(file_path),
                    line=line_number,
                    function=None,
                    language="sql",
                    source_kind="sql_file",
                ),
                confidence=1.0,
            )
        )

    return candidates


def _split_sql_statements(source: str) -> list[tuple[str, int]]:
    statements: list[tuple[str, int]] = []
    start = 0
    in_single = False
    in_double = False
    escaped = False

    for idx, char in enumerate(source):
        if escaped:
            escaped = False
            continue
        if char == "\\":
            escaped = True
            continue
        if char == "'" and not in_double:
            in_single = not in_single
            continue
        if char == '"' and not in_single:
            in_double = not in_double
            continue
        if char == ";" and not in_single and not in_double:
            chunk = source[start:idx].strip()
            if chunk:
                statements.append((chunk, start))
            start = idx + 1

    tail = source[start:].strip()
    if tail:
        statements.append((tail, start))

    return statements


def _sanitize_sql_statement(statement: str) -> str:
    # Drop MySQL dump directives and block comments (including /*! ... */ forms).
    text = re.sub(r"/\*![\s\S]*?\*/", " ", statement)
    text = re.sub(r"/\*[\s\S]*?\*/", " ", text)

    lines: list[str] = []
    for raw_line in text.splitlines():
        stripped = raw_line.strip()
        if not stripped:
            continue
        if stripped.startswith("--") or stripped.startswith("#"):
            continue
        if stripped.upper().startswith("DELIMITER "):
            continue
        lines.append(raw_line)

    return "\n".join(lines).strip()
