from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any, Literal

SourceKind = Literal["raw_sql", "orm_pattern", "sql_file", "wasm_sql"]
StatementKind = Literal["select", "insert", "update", "delete", "merge", "replace", "ddl", "other"]


@dataclass(frozen=True)
class QueryContext:
    file_path: str
    line: int
    function: str | None
    language: str
    source_kind: SourceKind


@dataclass
class QueryCandidate:
    sql: str
    context: QueryContext
    confidence: float = 1.0
    metadata: dict[str, Any] = field(default_factory=dict)


@dataclass
class ParseFailure:
    query: QueryCandidate
    error: str


@dataclass
class ParsedQueryFeatures:
    query: QueryCandidate
    statement_kind: StatementKind
    tables: list[str]
    where_columns: list[tuple[str, str]]
    join_columns: list[tuple[str, str]]
    order_by_columns: list[tuple[str, str]]
    group_by_columns: list[tuple[str, str]]
    equality_columns_by_table: dict[str, list[str]]


@dataclass
class ColumnUsage:
    where_count: int = 0
    join_count: int = 0
    order_count: int = 0
    group_count: int = 0


@dataclass
class WorkloadStats:
    total_queries: int
    table_query_count: dict[str, int] = field(default_factory=dict)
    table_read_count: dict[str, int] = field(default_factory=dict)
    table_write_count: dict[str, int] = field(default_factory=dict)
    column_usage: dict[str, dict[str, ColumnUsage]] = field(default_factory=dict)
    composite_filters: dict[str, dict[tuple[str, ...], int]] = field(default_factory=dict)
    where_order_patterns: dict[str, dict[tuple[tuple[str, ...], tuple[str, ...]], int]] = field(default_factory=dict)


@dataclass
class IndexSuggestion:
    table: str
    columns: list[str]
    index_name: str
    kind: str
    score: float
    confidence: float
    reason: str
    evidence: dict[str, int]
    ddl: str
    needs_manual_review: bool
    orm_snippets: dict[str, str]
    metadata: dict[str, Any] = field(default_factory=dict)


@dataclass
class ScanResult:
    scanned_files: list[str]
    candidates: list[QueryCandidate]
    parsed_queries: list[ParsedQueryFeatures]
    parse_failures: list[ParseFailure]
    workload: WorkloadStats
    suggestions: list[IndexSuggestion]
    warnings: list[str] = field(default_factory=list)
    metadata: dict[str, Any] = field(default_factory=dict)
