from __future__ import annotations

from auraindex.analyzers.schema_checks import ExistingIndex
from auraindex.models import IndexSuggestion, WorkloadStats


def build_schema_drift_report(
    workload: WorkloadStats,
    suggestions: list[IndexSuggestion],
    existing_indexes: list[ExistingIndex],
) -> dict[str, object]:
    referenced_columns: dict[str, set[str]] = {}
    for table, columns in workload.column_usage.items():
        referenced_columns[table] = set(columns.keys())

    possibly_unused: list[dict[str, object]] = []
    for index in existing_indexes:
        if index.unique:
            continue
        table_columns = referenced_columns.get(index.table, set())
        if not table_columns:
            possibly_unused.append(_existing_index_to_dict(index, "no_table_usage_observed"))
            continue
        if not set(index.columns).intersection(table_columns):
            possibly_unused.append(_existing_index_to_dict(index, "columns_not_observed_in_query_patterns"))

    missing_candidates: list[dict[str, object]] = []
    for suggestion in suggestions:
        impact = suggestion.metadata.get("impact", {})
        missing_candidates.append(
            {
                "index_name": suggestion.index_name,
                "table": suggestion.table,
                "columns": suggestion.columns,
                "reason": suggestion.reason,
                "impact_level": impact.get("impact_level"),
                "net_impact": impact.get("net_impact"),
            }
        )

    return {
        "summary": {
            "possibly_unused_existing_indexes": len(possibly_unused),
            "missing_index_candidates": len(missing_candidates),
        },
        "possibly_unused_existing_indexes": possibly_unused[:100],
        "missing_index_candidates": missing_candidates[:100],
    }


def _existing_index_to_dict(index: ExistingIndex, reason: str) -> dict[str, object]:
    return {
        "name": index.name,
        "table": index.table,
        "columns": index.columns,
        "unique": index.unique,
        "partial_where": index.partial_where,
        "source_file": index.source_file,
        "source_line": index.source_line,
        "reason": reason,
    }
