"""altimate-core — Type-check your SQL. No database required.

Call ``altimate_core.init(...)`` before using gated functions (``column_lineage``,
``track_lineage``). All other functions work without configuration.
"""

import atexit
import json
from pathlib import Path
from typing import Optional

import altimate_core._core as _core

__all__ = [
    "init",
    "Schema",
    "column_lineage",
    "validate",
    "explain",
    "fix",
    "check_policy",
    "transpile",
    "format_sql",
    "extract_metadata",
    "extract_output_columns",
    "compare_queries",
    "lint",
    "scan_sql",
    "is_safe",
    "classify_pii",
    "check_query_pii",
    "check_semantics",
    "resolve_term",
    "track_lineage",
    "estimate_cost",
    "complexity_score",
    "check_equivalence",
    "correct",
    "evaluate",
    "complete",
    "rewrite",
    "generate_tests",
    "analyze_migration",
    "parse_dbt_project",
    "optimize_context",
    "optimize_for_query",
    "prune_schema",
    "diff_schemas",
    "import_ddl",
    "export_ddl",
    "schema_fingerprint",
    "introspection_sql",
]

Schema = _core.Schema

_CONFIG_PATH = Path.home() / ".altimate" / "altimate.json"
_atexit_registered = False


def _load_config_file() -> Optional[dict]:
    """Read ~/.altimate/altimate.json if it exists."""
    try:
        return json.loads(_CONFIG_PATH.read_text())
    except (FileNotFoundError, json.JSONDecodeError, OSError):
        return None


def init(
    api_key: Optional[str] = None,
    *,
    caller: Optional[dict] = None,
    report_failures: bool = True,
    telemetry: bool = True,
    backend_url: Optional[str] = None,
):
    """Initialize altimate_core credentials.

    Required before calling ``column_lineage`` or ``track_lineage``.
    All other functions work without initialization.

    Args:
        api_key: API key (default: from config file ``altimateApiKey``).
        caller: Dict with ``tenant`` key (default: from config file ``altimateInstanceName``).
        report_failures: Report empty lineage to backend (default True).
        telemetry: Send anonymous usage events to App Insights (default True).
            Disable with ``telemetry=False`` or ``ALTIMATE_CORE_TELEMETRY=0``.
        backend_url: Backend URL (default: from config file ``altimateUrl``).
    """
    file_cfg = _load_config_file() or {}

    resolved_api_key = api_key or file_cfg.get("altimateApiKey")
    resolved_backend_url = (
        backend_url
        or file_cfg.get("altimateUrl", "https://api.myaltimate.com")
    )

    if caller is not None:
        tenant = caller.get("tenant") if isinstance(caller, dict) else caller.tenant
    elif file_cfg.get("altimateInstanceName"):
        tenant = file_cfg["altimateInstanceName"]
    else:
        tenant = None

    if not resolved_api_key:
        raise RuntimeError(
            'No API key found. Pass api_key to init() or set "altimateApiKey" in ~/.altimate/altimate.json'
        )
    if not tenant:
        raise RuntimeError(
            'No tenant found. Pass caller={"tenant": "..."} to init() or set "altimateInstanceName" in ~/.altimate/altimate.json'
        )

    _core._init_sdk(resolved_api_key, tenant, resolved_backend_url, report_failures, telemetry)

    global _atexit_registered
    if not _atexit_registered:
        atexit.register(_core._flush_sdk)
        _atexit_registered = True


# ---------------------------------------------------------------------------
# All functions — direct passthrough to compiled Rust core
# ---------------------------------------------------------------------------

# Gated (require init + credits)
column_lineage = _core.column_lineage
track_lineage = _core.track_lineage

# Ungated (work without init)
validate = _core.validate
explain = _core.explain
fix = _core.fix
check_policy = _core.check_policy
transpile = _core.transpile
format_sql = _core.format_sql
extract_metadata = _core.extract_metadata
extract_output_columns = _core.extract_output_columns
compare_queries = _core.compare_queries
lint = _core.lint
scan_sql = _core.scan_sql
is_safe = _core.is_safe
classify_pii = _core.classify_pii
check_query_pii = _core.check_query_pii
check_semantics = _core.check_semantics
resolve_term = _core.resolve_term
estimate_cost = _core.estimate_cost
complexity_score = _core.complexity_score
check_equivalence = _core.check_equivalence
correct = _core.correct
evaluate = _core.evaluate
complete = _core.complete
rewrite = _core.rewrite
generate_tests = _core.generate_tests
analyze_migration = _core.analyze_migration
parse_dbt_project = _core.parse_dbt_project
optimize_context = _core.optimize_context
optimize_for_query = _core.optimize_for_query
prune_schema = _core.prune_schema
diff_schemas = _core.diff_schemas
import_ddl = _core.import_ddl
export_ddl = _core.export_ddl
schema_fingerprint = _core.schema_fingerprint
introspection_sql = _core.introspection_sql
