from __future__ import annotations

import os
from pathlib import Path

import uvicorn

from external_connector.app import create_app
from external_connector.providers.composite import CompositeProvider
from external_connector.providers.fake import FakeProvider
from external_connector.providers.feishu_bot import FeishuBotProvider
from external_connector.providers.vendor_cli import VendorCliProvider
from external_connector.providers.weixin_ilink import WeixinIlinkProvider
from external_connector.state import SidecarStateStore


def build_app():
    home = Path(os.getenv("CONNECTOR_HOME", "/var/lib/external-connector"))
    store = SidecarStateStore(home / "state.json")
    provider_name = os.getenv("CONNECTOR_PROVIDER", "fake")
    if provider_name == "official":
        provider = CompositeProvider([
            _weixin_provider(store),
            _feishu_provider(store),
        ])
    elif provider_name == "weixin_ilink":
        provider = _weixin_provider(store)
    elif provider_name == "feishu_bot":
        provider = _feishu_provider(store)
    elif provider_name == "vendor_cli":
        provider = VendorCliProvider(store=store, env=os.environ)
    else:
        provider = FakeProvider(store)
    return create_app(provider=provider, api_token=os.getenv("CONNECTOR_API_TOKEN", ""))


def _weixin_provider(store: SidecarStateStore) -> WeixinIlinkProvider:
    return WeixinIlinkProvider(
        store=store,
        bridge_base_url=os.getenv("BEAVER_BRIDGE_BASE_URL", ""),
        bridge_token=os.getenv("BEAVER_BRIDGE_TOKEN", ""),
    )


def _feishu_provider(store: SidecarStateStore) -> FeishuBotProvider:
    return FeishuBotProvider(
        store=store,
        bridge_base_url=os.getenv("BEAVER_BRIDGE_BASE_URL", ""),
        public_base_url=os.getenv("CONNECTOR_PUBLIC_BASE_URL", ""),
        bridge_token=os.getenv("BEAVER_BRIDGE_TOKEN", ""),
    )


app = build_app()


def main() -> None:
    uvicorn.run(app, host="0.0.0.0", port=8787)


if __name__ == "__main__":
    main()
