"""Logos ADK — Framework for building AI agents.

Stable public API surface. For full module access, import from submodules directly.

Example:
    from logos_adk import Agent, Tool, Memory
    from logos_adk.agent import Agent
    from logos_adk.memory import Memory, SessionMemory
"""

from __future__ import annotations

# =============================================================================
# Version
# =============================================================================
from logos_adk.version import (
    __version__,
    API_VERSION,
    STABILITY_POLICY,
    PUBLIC_API_MODULES,
    PUBLIC_IMPORT_ROOT,
    PRIVATE_MODULE_PREFIXES,
)

# =============================================================================
# Core Agent API
# =============================================================================
from logos_adk.agent import Agent
from logos_adk.state import AgentState
from logos_adk.runnable import Runnable

# =============================================================================
# Tools
# =============================================================================
from logos_adk.tools import Tool, tool
from logos_adk.tools.toolkit import Toolkit
from logos_adk.tools.artifacts import ArtifactToolkit
from logos_adk.tools.temporal import TemporalToolkit
from logos_adk.tools.registry import tool_registry as registry

# =============================================================================
# Memory
# =============================================================================
from logos_adk.memory import (
    Memory,
    MemoryBackend,
    MemoryEntry,
    SessionMemory,
    LongTermMemory,
    SharedMemory,
)
from logos_adk.memory.backends import (
    InMemoryBackend,
    ShardedMemoryBackend,
    SQLiteBackend,
)

# =============================================================================
# State & Config
# =============================================================================
from logos_adk.config import (
    AgentConfig,
    ContextWindowConfig,
    RateLimitConfig,
    ReliabilityConfig,
    RoutingConfig,
    SecurityConfig,
    SelfQAConfig,
    StateConfig,
)
from logos_adk.config_loader import (
    build_agent_config,
    load_agent_config,
    load_agent_from_config,
)
from logos_adk.config_parser import parse_agent_config_data

# =============================================================================
# Observability
# =============================================================================
from logos_adk.observe import (
    Exporter,
    Span,
    Metric,
    AlertEvent,
    AlertRule,
    ConsoleExporter,
    InMemoryExporter,
    LangfuseExporter,
    OpenTelemetryExporter,
)

# =============================================================================
# Types
# =============================================================================
from logos_adk.types import (
    ContentPart,
    Message,
    Response,
    StreamChunk,
    StreamDone,
    TextChunk,
    ToolCall,
    ToolResult,
    ToolStart,
    ToolEnd,
    Usage,
    content_text,
    normalize_content_parts,
    MediaChunk,
    StructuredResponse,
    AgentDelegation,
    has_media_content,
)

# =============================================================================
# Errors
# =============================================================================
from logos_adk.errors import (
    LogosError,
    BudgetExhaustedError,
    CircuitBreakerOpenError,
    GuardrailError,
    InputValidationError,
    PIIDetectedError,
    PromptInjectionError,
    ProviderTimeoutError,
    SecurityError,
)

# =============================================================================
# Reliability & Security
# =============================================================================
from logos_adk.reliability import CircuitBreaker, RetryPolicy
from logos_adk.security import (
    AuditLogger,
    InputValidator,
    PIIDetector,
    PromptShield,
)

# =============================================================================
# Budget & Spend Tracking
# =============================================================================
from logos_adk.budgeting import BudgetAccount, BudgetStatus
from logos_adk.spend_ledger import (
    SpendRecord,
    SpendBudgetStatus,
    InMemorySpendLedger,
    SQLiteSpendLedger,
    PostgreSQLSpendLedger,
)

# =============================================================================
# Event Bus & Swarm
# =============================================================================
from logos_adk.event_bus import EventBus, EventRecord, InMemoryEventBus
from logos_adk.swarm import Swarm

# =============================================================================
# Crew & Team
# =============================================================================
from logos_adk.team import Team, CampaignState
from logos_adk.crew import (
    CrewTask,
    CrewResult,
    CrewProcess,
    CrewProcessMode,
)

# =============================================================================
# Workflow & Planning
# =============================================================================
from logos_adk.workflow import (
    Graph,
    Pipeline,
    Node,
    Edge,
    Step,
)
from logos_adk.planning import PlanAndExecute

# =============================================================================
# RAG
# =============================================================================
from logos_adk.rag import (
    Chunk,
    Document,
    KnowledgeBase,
    VectorStore,
    InMemoryVectorStore,
    TextSplitter,
    RecursiveCharacterSplitter,
    rag_tool,
)

# =============================================================================
# Testing
# =============================================================================
from logos_adk.testing import (
    mock_agent,
    assert_response,
    assert_tool_called,
    assert_tool_not_called,
)


# =============================================================================
# Registry & Advanced Features (lazy)
# =============================================================================
def __getattr__(name: str):
    """Lazy import for heavy/optional modules."""

    # Agent Registry
    if name in (
        "AgentClassRegistry",
        "AgentFactoryRegistry",
        "agent_class",
        "agent_factory",
        "agent_class_registry",
        "agent_factory_registry",
    ):
        from logos_adk.agent_registry import (
            AgentClassRegistry,
            AgentFactoryRegistry,
            agent_class,
            agent_class_registry,
            agent_factory,
            agent_factory_registry,
        )

        return locals()[name]

    # Diffusion
    if name in (
        "Automatic1111DiffusionBackend",
        "DiffusionBackend",
        "DiffusionImageResult",
        "build_diffusion_backend",
    ):
        from logos_adk.diffusion import (
            Automatic1111DiffusionBackend,
            DiffusionBackend,
            DiffusionImageResult,
            build_diffusion_backend,
        )

        return locals()[name]

    # Dynamic Orchestration
    if name in (
        "DepartmentSupervisor",
        "DepartmentSpec",
        "DepartmentConfig",
        "DepartmentRoutingDecisionSchema",
        "DepartmentSupervisorConfig",
        "SwarmSubscriptionConfig",
        "load_department_supervisor_config",
        "load_department_supervisor_from_config",
        "parse_department_supervisor_config_data",
    ):
        from logos_adk.dynamic_orchestration import (
            DepartmentSupervisor,
            DepartmentSpec,
            DepartmentRoutingDecisionSchema,
        )
        from logos_adk.dynamic_orchestration_config import (
            DepartmentConfig,
            DepartmentSupervisorConfig,
            SwarmSubscriptionConfig,
        )
        from logos_adk.dynamic_orchestration_config_parser import (
            load_department_supervisor_config,
            load_department_supervisor_from_config,
            parse_department_supervisor_config_data,
        )

        return locals()[name]

    # MCP
    if name in ("MCPClient", "serve_as_mcp", "serve_as_mcp_async"):
        from logos_adk.mcp import MCPClient, serve_as_mcp, serve_as_mcp_async

        return locals()[name]

    # Guardrails
    if name in (
        "Guardrail",
        "GuardrailResult",
        "ContentFilter",
        "ContentModerationGuard",
        "ToxicityGuard",
        "HallucinationGuard",
        "MaxLengthGuard",
        "KeywordGuard",
        "RegexGuard",
    ):
        from logos_adk.guardrails import (
            Guardrail,
            GuardrailResult,
            ContentFilter,
            ContentModerationGuard,
            ToxicityGuard,
            HallucinationGuard,
            MaxLengthGuard,
            KeywordGuard,
            RegexGuard,
        )

        return locals()[name]

    # Quality & Testing (heavy)
    if name in ("LLMJudge", "run_llm_judge_eval", "run_golden_dataset"):
        from logos_adk.testing_framework import (
            LLMJudge,
            run_llm_judge_eval,
            run_golden_dataset,
            run_integration_suite,
            run_load_test,
            GoldenExample,
            JudgeCase,
            JudgeResult,
            LoadTestConfig,
            LoadTestReport,
        )

        return locals()[name]

    # Quality History
    if name in (
        "QualityHistoryStore",
        "SQLiteQualityHistoryStore",
        "get_quality_execution_manager",
    ):
        from logos_adk.quality_history import (
            QualityHistoryStore,
            SQLiteQualityHistoryStore,
            PostgreSQLQualityHistoryStore,
            QualityRunRecord,
            QualityExecutionManager,
            build_quality_history_store,
            get_quality_execution_manager,
        )

        return locals()[name]

    # Self-QA
    if name in ("SelfQAAssertion", "SelfQAAttempt", "SelfQACheck", "SelfQAReport", "SelfQAVerdict"):
        from logos_adk.self_qa import (
            SelfQAAssertion,
            SelfQAAttempt,
            SelfQACheck,
            SelfQAReport,
            SelfQAVerdict,
        )

        return locals()[name]

    # Chronos
    if name == "Chronos":
        from logos_adk.chronos import Chronos

        return Chronos

    # Artifact
    if name in ("ArtifactRecord", "ArtifactSandbox", "artifact_sandbox"):
        from logos_adk.artifacts import (
            ArtifactRecord,
            ArtifactSandbox,
            artifact_sandbox,
        )

        return locals()[name]

    # Semantic Cache
    if name == "SemanticCache":
        from logos_adk.semantic_cache import SemanticCache

        return SemanticCache

    # Auto Context
    if name == "get_model_context_limit":
        from logos_adk.auto_context import get_model_context_limit

        return get_model_context_limit

    # Generated Tools
    if name in (
        "GeneratedToolArtifact",
        "GeneratedToolStore",
        "develop_tool",
        "generated_tool_store",
    ):
        from logos_adk.tool_synthesis import (
            GeneratedToolArtifact,
            GeneratedToolStore,
            develop_tool,
            generated_tool_store,
        )

        return locals()[name]

    # Serve (optional)
    if name in ("serve", "create_app", "create_app_from_config_paths", "serve_from_config_paths"):
        try:
            from logos_adk.serve import (
                serve,
                create_app,
                create_app_from_config_paths,
                serve_from_config_paths,
            )

            return locals()[name]
        except ImportError:
            pass

    # Providers
    if name == "GeminiProvider":
        from logos_adk.providers.gemini import GeminiProvider

        return GeminiProvider

    if name == "OpenAIResponsesProvider":
        from logos_adk.providers.openai_responses import OpenAIResponsesProvider

        return OpenAIResponsesProvider

    if name == "OpenAICompatibleProvider":
        try:
            from logos_adk.providers.openai import OpenAICompatibleProvider

            return OpenAICompatibleProvider
        except ImportError:
            pass

    # Cache backends (optional)
    if name == "RedisCacheBackend":
        try:
            from logos_adk.cache.redis import RedisCacheBackend

            return RedisCacheBackend
        except ImportError:
            pass

    if name == "PostgreSQLCacheBackend":
        try:
            from logos_adk.cache.postgresql import PostgreSQLCacheBackend

            return PostgreSQLCacheBackend
        except ImportError:
            pass

    # Vector stores (optional)
    if name == "SQLiteVectorStore":
        try:
            from logos_adk.rag.vector_sqlite import SQLiteVectorStore

            return SQLiteVectorStore
        except ImportError:
            pass

    if name == "PostgreSQLVectorStore":
        try:
            from logos_adk.rag.vector_postgresql import PostgreSQLVectorStore

            return PostgreSQLVectorStore
        except ImportError:
            pass

    if name == "ChromaVectorStore":
        try:
            from logos_adk.rag.vector_chroma import ChromaVectorStore

            return ChromaVectorStore
        except ImportError:
            pass

    # Runnable config
    if name in (
        "RunnableConfigKind",
        "load_runnable_from_config",
        "describe_runnable_from_config",
        "detect_runnable_config_kind",
    ):
        from logos_adk.runnable_config_loader import (
            RunnableConfigKind,
            load_runnable_from_config,
            describe_runnable_from_config,
            detect_runnable_config_kind,
        )

        return locals()[name]

    # Crew checkpoint
    if name in ("PostgreSQLCrewCheckpointStore", "PostgreSQLGraphCheckpointStore"):
        from logos_adk.crew_checkpoint_store import (
            PostgreSQLCrewCheckpointStore,
            CREW_CHECKPOINT_SCHEMA_KIND,
            CREW_CHECKPOINT_SCHEMA_VERSION,
            CrewCheckpointRecord,
            CrewCheckpointStore,
            InMemoryCrewCheckpointStore,
            SQLiteCrewCheckpointStore,
        )
        from logos_adk.graph_checkpoint_store import (
            PostgreSQLGraphCheckpointStore,
            GRAPH_CHECKPOINT_SCHEMA_KIND,
            GRAPH_CHECKPOINT_SCHEMA_VERSION,
            GraphCheckpointRecord,
            GraphCheckpointStore,
            InMemoryGraphCheckpointStore,
            SQLiteGraphCheckpointStore,
        )

        return locals()[name]

    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")


# =============================================================================
# Public API
# =============================================================================

__all__ = [
    # Version
    "__version__",
    "API_VERSION",
    "STABILITY_POLICY",
    # Core
    "Agent",
    "Runnable",
    "AgentState",
    # Registry
    "AgentClassRegistry",
    "AgentFactoryRegistry",
    "agent_class",
    "agent_factory",
    "agent_class_registry",
    "agent_factory_registry",
    # Tools
    "Tool",
    "tool",
    "Toolkit",
    "ArtifactToolkit",
    "TemporalToolkit",
    "registry",
    # Memory
    "Memory",
    "MemoryBackend",
    "MemoryEntry",
    "SessionMemory",
    "LongTermMemory",
    "SharedMemory",
    "InMemoryBackend",
    "ShardedMemoryBackend",
    "SQLiteBackend",
    # Config
    "AgentConfig",
    "ContextWindowConfig",
    "RateLimitConfig",
    "ReliabilityConfig",
    "RoutingConfig",
    "SecurityConfig",
    "SelfQAConfig",
    "StateConfig",
    "build_agent_config",
    "load_agent_config",
    "load_agent_from_config",
    "parse_agent_config_data",
    # Observability
    "Exporter",
    "Span",
    "Metric",
    "AlertEvent",
    "AlertRule",
    "ConsoleExporter",
    "InMemoryExporter",
    "LangfuseExporter",
    "OpenTelemetryExporter",
    # Types
    "ContentPart",
    "Message",
    "Response",
    "StreamChunk",
    "StreamDone",
    "TextChunk",
    "ToolCall",
    "ToolResult",
    "ToolStart",
    "ToolEnd",
    "Usage",
    "content_text",
    "normalize_content_parts",
    "MediaChunk",
    "StructuredResponse",
    "AgentDelegation",
    "has_media_content",
    # Errors
    "LogosError",
    "BudgetExhaustedError",
    "CircuitBreakerOpenError",
    "GuardrailError",
    "InputValidationError",
    "PIIDetectedError",
    "PromptInjectionError",
    "ProviderTimeoutError",
    "SecurityError",
    # Reliability & Security
    "CircuitBreaker",
    "RetryPolicy",
    "AuditLogger",
    "InputValidator",
    "PIIDetector",
    "PromptShield",
    # Budget
    "BudgetAccount",
    "BudgetStatus",
    "SpendRecord",
    "SpendBudgetStatus",
    "InMemorySpendLedger",
    "SQLiteSpendLedger",
    "PostgreSQLSpendLedger",
    # Event Bus & Swarm
    "EventBus",
    "EventRecord",
    "InMemoryEventBus",
    "Swarm",
    # Crew & Team
    "Team",
    "CampaignState",
    "CrewTask",
    "CrewResult",
    "CrewProcess",
    "CrewProcessMode",
    "CrewRoutingDecisionSchema",
    "CrewTaskResult",
    "CrewTaskType",
    "serialize_crew_result",
    "DepartmentRoutingDecisionSchema",
    "DepartmentConfig",
    "DepartmentSpec",
    "DepartmentSupervisor",
    "DepartmentSupervisorConfig",
    "SwarmSubscriptionConfig",
    "load_department_supervisor_config",
    "load_department_supervisor_from_config",
    "parse_department_supervisor_config_data",
    # Workflow & Planning
    "Graph",
    "Pipeline",
    "Node",
    "Edge",
    "Step",
    "PlanAndExecute",
    "ReWOOAgent",
    "PlanStep",
    "ExecutionPlan",
    "ExecutedPlanStep",
    # RAG
    "Chunk",
    "Document",
    "KnowledgeBase",
    "VectorStore",
    "InMemoryVectorStore",
    "TextSplitter",
    "RecursiveCharacterSplitter",
    "rag_tool",
    "DocumentLoadError",
    "DocumentLoader",
    "RAGMemory",
    # Testing
    "mock_agent",
    "assert_response",
    "assert_tool_called",
    "assert_tool_not_called",
    "assert_guardrail_blocked",
    # Artifacts
    "ArtifactRecord",
    "ArtifactSandbox",
    "artifact_sandbox",
    # Generated Tools
    "GeneratedToolArtifact",
    "GeneratedToolStore",
    "develop_tool",
    "generated_tool_store",
    # Self-QA
    "SelfQAAssertion",
    "SelfQAAttempt",
    "SelfQACheck",
    "SelfQAReport",
    "SelfQAVerdict",
    # Chronos
    "Chronos",
    # Runnable Config
    "RunnableConfigKind",
    "load_runnable_from_config",
    "describe_runnable_from_config",
    "detect_runnable_config_kind",
    # Crew Checkpoint
    "PostgreSQLCrewCheckpointStore",
    "PostgreSQLGraphCheckpointStore",
    "CREW_CHECKPOINT_SCHEMA_KIND",
    "CREW_CHECKPOINT_SCHEMA_VERSION",
    "CrewCheckpointRecord",
    "CrewCheckpointStore",
    "InMemoryCrewCheckpointStore",
    "SQLiteCrewCheckpointStore",
    "GRAPH_CHECKPOINT_SCHEMA_KIND",
    "GRAPH_CHECKPOINT_SCHEMA_VERSION",
    "GraphCheckpointRecord",
    "GraphCheckpointStore",
    "InMemoryGraphCheckpointStore",
    "SQLiteGraphCheckpointStore",
    # Providers
    "GeminiProvider",
    "OpenAIResponsesProvider",
    "OpenAICompatibleProvider",
    # Serve
    "serve",
    "create_app",
    "create_app_from_config_paths",
    "serve_from_config_paths",
]
