import asyncio
import logging

from maps_adv.billing_proxy.lib.config import config
from maps_adv.billing_proxy.lib.core.async_xmlrpc_client import XmlRpcClient
from maps_adv.billing_proxy.lib.core.balance_client import BalanceClient
from maps_adv.billing_proxy.lib.data_manager import ClientsDataManager
from maps_adv.billing_proxy.lib.db.engine import DB
from maps_adv.billing_proxy.lib.domain import ClientsDomain

from smb.common.aiotvm import TvmClient


async def really_main(config):
    async with TvmClient(
        f"localhost:{config['TVMTOOL_PORT']}", config["TVMTOOL_LOCAL_AUTHTOKEN"]
    ) as tvm_client:
        xmlrpc_client = XmlRpcClient(
            host=config["BALANCE_XMLRPC_API_HOST"],
            port=config["BALANCE_XMLRPC_API_PORT"],
            path=config["BALANCE_XMLRPC_API_PATH"],
            use_https=True,
            tvm_client=tvm_client,
            tvm_destination="balance",
        )
        db = await DB.create(config["DATABASE_URL"])

        try:
            domain = ClientsDomain(
                ClientsDataManager(db=db),
                BalanceClient(
                    default_service_id=config["BALANCE_SERVICE_ID"],
                    service_tokens={
                        config["BALANCE_SERVICE_ID"]: config["BALANCE_SERVICE_TOKEN"]
                    },
                    operator_uid=config["BALANCE_OPERATOR_UID"],
                    xmlrpc_client=xmlrpc_client,
                ),
            )
            await domain.sync_clients_data_and_contracts_with_balance()
        finally:
            await xmlrpc_client.close()
            await db.close()


def main():
    logging.basicConfig(level=logging.DEBUG)
    config.init()

    asyncio.run(really_main(config))
