import asyncio
import os
from typing import Dict, Type

import tornado
from tornado.routing import _RuleList

from aext_shared.backend_proxy import ProxyResponse
from aext_shared.config import get_config
from aext_shared.errors import BadRequest
from aext_shared.handler import BackendHandler, create_rules

config = get_config()


class ConfigHandler(BackendHandler):
    @tornado.web.authenticated
    async def get(self):
        self.finish(config)


class FeatureFlagInitHandler(BackendHandler):
    @tornado.web.authenticated
    async def get(self):
        [account, organizations] = await asyncio.gather(
            self.anaconda_cloud_proxy("account"),
            self.anaconda_cloud_proxy("organizations/my"),
        )
        data = account["remote_data"]
        # Keep in sync with passport_to_feature_flag_user in nucleus
        # https://github.com/anaconda/bigbend-platform/blob/main/shared/python/shared/feature_flags.py#L83
        email: str = data["user"].get("email", "")
        is_confirmed: bool = data["profile"]["is_confirmed"]
        is_disabled: bool = data["profile"]["is_disabled"]
        is_anaconda_email = email.lower().endswith("@anaconda.com") and is_confirmed and not is_disabled
        org_ids = [o["id"] for o in organizations["remote_data"]]

        feature_flag_context = {
            "key": f"user:{data['user']['id']}",
            "kind": "user",
            "confirmed": is_confirmed,
            "disabled": is_disabled,
            "is_anaconda_employee": is_anaconda_email,
            "org_ids": org_ids,
        }
        self.finish(ProxyResponse(remote_status_code=200, remote_data=feature_flag_context))


def get_routes(base_url: str) -> _RuleList:
    handlers: Dict[str, Type[BackendHandler]] = {
        "config": ConfigHandler,
        "feature_flag/init": FeatureFlagInitHandler,
    }
    return create_rules(base_url, "aext_core_server", handlers)
