"""Compatibility tests for dual namespace support and shim exports."""

from __future__ import annotations

import importlib
import subprocess
import sys
import warnings


def test_import_briefcase_ai_and_briefcase():
    import briefcase
    import briefcase_ai

    assert hasattr(briefcase_ai, "DecisionSnapshot")
    assert hasattr(briefcase, "integrations")


def test_shim_exports_present_on_briefcase_ai():
    import briefcase_ai

    assert callable(briefcase_ai.versioned)
    assert callable(briefcase_ai.lakefs_versioned)
    assert callable(briefcase_ai.versioned_context)
    assert callable(briefcase_ai.lakefs_context)
    assert callable(briefcase_ai.briefcase_workflow)


def test_shim_calls_emit_deprecation_warning():
    import briefcase_ai

    with warnings.catch_warnings(record=True) as caught:
        warnings.simplefilter("always", DeprecationWarning)
        decorator = briefcase_ai.versioned(repository="test-repo")
        assert callable(decorator)

    assert any(item.category is DeprecationWarning for item in caught)


def test_decorator_and_context_imports_from_both_namespaces():
    import briefcase_ai

    from briefcase.integrations.lakefs import versioned as legacy_versioned
    from briefcase.integrations.lakefs import versioned_context as legacy_context

    assert callable(legacy_versioned)
    assert callable(legacy_context)
    assert callable(briefcase_ai.versioned)
    assert callable(briefcase_ai.versioned_context)


def test_bridge_modules_import_from_briefcase_ai_namespace():
    import briefcase_ai.compliance as compliance
    import briefcase_ai.correlation as correlation
    import briefcase_ai.external_data as external_data
    import briefcase_ai.integrations as integrations
    import briefcase_ai.rag as rag
    import briefcase_ai.semantic_conventions as semantic_conventions
    import briefcase_ai.validation as validation
    import briefcase_ai.workflows as workflows

    assert integrations is not None
    assert correlation is not None
    assert compliance is not None
    assert rag is not None
    assert external_data is not None
    assert validation is not None
    assert semantic_conventions is not None
    assert workflows is not None


def test_nested_bridge_submodules_resolve():
    mod = importlib.import_module("briefcase_ai.integrations.lakefs")
    assert hasattr(mod, "versioned")

    mod = importlib.import_module("briefcase_ai.rag.vector_stores")
    assert hasattr(mod, "VersionedPineconeStore")

    mod = importlib.import_module("briefcase_ai.compliance.reports")
    assert hasattr(mod, "SOC2ReportGenerator")


def test_core_object_construction_and_serialization_surface():
    import briefcase_ai

    input_obj = briefcase_ai.Input("prompt", "Summarize this", "string")
    output_obj = briefcase_ai.Output("response", "summary", "string")
    output_obj.with_confidence(0.95)

    assert input_obj.to_dict()["name"] == "prompt"
    assert output_obj.to_dict()["confidence"] == 0.95

    decision = briefcase_ai.DecisionSnapshot("chat_completion")
    decision.add_input(input_obj)
    decision.add_output(output_obj)
    decision.with_execution_time(12.0)
    decision.add_tag("environment", "test")

    assert decision.function_name == "chat_completion"
    assert len(decision.inputs) == 1
    assert len(decision.outputs) == 1
    assert decision.tags["environment"] == "test"


def test_quickstart_storage_flow_works_with_primary_namespace():
    import briefcase_ai

    if not briefcase_ai.is_initialized():
        briefcase_ai.init_with_config(2)

    decision = briefcase_ai.DecisionSnapshot("chat_completion")
    decision.add_input(briefcase_ai.Input("prompt", "Hello", "string"))
    decision.add_output(briefcase_ai.Output("response", "Hi", "string"))

    storage = briefcase_ai.SqliteBackend.in_memory()
    decision_id = storage.save_decision(decision)
    loaded = storage.load_decision(decision_id)

    assert isinstance(decision_id, str)
    assert loaded.function_name == "chat_completion"


def test_quickstart_like_auxiliary_components():
    import briefcase_ai

    drift = briefcase_ai.DriftCalculator()
    metrics = drift.calculate_drift(["A", "A", "B"])
    assert "drift_score" in metrics.to_dict()

    cost = briefcase_ai.CostCalculator()
    estimate = cost.estimate_cost("gpt-4", 1200, 300)
    assert estimate.to_dict()["model_name"] == "gpt-4"

    sanitizer = briefcase_ai.Sanitizer()
    sanitized = sanitizer.sanitize("Email me at user@example.com")
    assert sanitized.to_dict()["has_redactions"] is True


def test_init_registers_atexit_without_name_error():
    script = """
import briefcase_ai
briefcase_ai.init()
print(briefcase_ai.is_initialized())
"""
    proc = subprocess.run(
        [sys.executable, "-c", script],
        capture_output=True,
        text=True,
        check=False,
    )
    assert proc.returncode == 0, proc.stderr
    assert "True" in proc.stdout
