from datetime import UTC, datetime

from zbt.core.config import Settings
from zbt.infrastructure.mysql.analytics_queries import SqlAlchemyOperationalAnalytics
from zbt.infrastructure.mysql.sessions import (
    DatabaseName,
    create_mysql_engine,
    create_session_factory,
)


def build_analytics_foundation(settings: Settings | None = None) -> None:
    resolved_settings = settings or Settings()
    core_engine = create_mysql_engine(resolved_settings, DatabaseName.CORE)
    analytics_engine = create_mysql_engine(
        resolved_settings,
        DatabaseName.ANALYTICS,
    )
    service = SqlAlchemyOperationalAnalytics(
        create_session_factory(core_engine),
        create_session_factory(analytics_engine),
        lambda: datetime.now(UTC),
    )
    result = service.refresh()
    core_engine.dispose()
    analytics_engine.dispose()
    print(
        "Analytics 已同步："
        f"产品{result['products']}、业务员{result['salespeople']}、"
        f"订单{result['orders']}、保单{result['policies']}。"
    )


if __name__ == "__main__":
    build_analytics_foundation()
