from __future__ import annotations

from app.core.config import get_settings
from app.schema.loader import load_schema_contract
from app.schema.registry import SchemaRegistry, build_snapshot


def test_supplied_schema_contract_parses_real_tables_and_keys():
    tables = load_schema_contract(get_settings().schema_source_path)

    assert len(tables) == 40  # 37 + zb_recurring_invoices, zb_credit_note_invoices, zb_vendor_credit_line_items
    assert "vendors" in tables
    assert "customers" in tables
    assert "users" in tables
    assert "zb_recurring_invoices" in tables and "recurrence_frequency" in tables["zb_recurring_invoices"].columns
    assert "is_active" in tables["qbo_tokens"].columns
    assert tables["vendors"].columns["id"].primary_key is True
    assert tables["vendors"].foreign_keys[0].referred_table == "users"
    assert "outstanding_payable_amount" in tables["vendors"].columns


def test_registry_uses_schema_contract_without_database_introspection():
    registry = SchemaRegistry()
    snapshot = registry.refresh(get_settings().schema_source_path)

    assert snapshot.has_table("vendors")
    assert snapshot.has_column("vendors", "company_name")
    assert snapshot.has_table("users")
    assert snapshot.get_direct_relationships("vendors", "users")


def test_build_snapshot_matches_registry_refresh():
    """The standalone helper `scripts/validate_schema.py` relies on must stay
    in lockstep with what `SchemaRegistry.refresh()` actually does at
    startup, or a schema change could pass validation and still fail to boot."""
    settings = get_settings()

    standalone = build_snapshot(settings.schema_source_path, settings.schema_customizations_path)
    registry_snapshot = SchemaRegistry().refresh(settings.schema_source_path)

    assert set(standalone.tables) == set(registry_snapshot.tables)
    assert len(standalone.relationships) == len(registry_snapshot.relationships)


def test_datetime_type_is_not_misclassified_as_date(tmp_path):
    from app.schema.registry import build_snapshot

    snapshot = build_snapshot("app/schema/oremus.sql", "schema_customizations.json")
    assert snapshot.column_type("customers", "zoho_created_time") == "datetime"
    assert snapshot.column_type("customers", "zoho_last_modified_time") == "datetime"
    assert snapshot.column_type("customers", "synced_at") == "datetime"
