import json
from typing import Optional, Tuple

from clarabot_nano_common.common.config.constants import CommonConfigConstants
from clarabot_nano_common.utility.path.common import normalize_validate_resolve_absolute_path


def parse_development_server_config(config: dict) -> Tuple[str, str, str]:
    config.pop("start_time", None)
    server_frontend_domain = config.pop("server_frontend_domain", None)
    server_frontend_path = config.pop("server_frontend_path", "/api/")  # "/" historically
    ca_path = config.pop("ca_path", None)
    ca_certificate = config.pop("ca_certificate", None)
    assert not config, f"Unknown development-server-config input: {config}"
    if ca_certificate:
        pass
    elif ca_path:
        ca_certificate = normalize_validate_resolve_absolute_path(ca_path).read_text()
    else:
        assert False, "No CA certificate in development-server-config input"
    assert server_frontend_domain, "No server domain in development-server-config input"
    assert server_frontend_path, "No server path in development-server-config input"
    return server_frontend_domain, server_frontend_path, ca_certificate


def load_development_server_config(server_config_path: Optional[str]):
    if not server_config_path:
        return
    server_config_path = normalize_validate_resolve_absolute_path(server_config_path)
    with server_config_path.open("rb") as f:
        config = json.load(f)
    server_frontend_domain, server_frontend_path, ca_certificate = parse_development_server_config(config)
    CommonConfigConstants.SERVER_DOMAIN = server_frontend_domain
    CommonConfigConstants.SERVER_PATH = server_frontend_path
    CommonConfigConstants.AIOHTTP_CLIENT_SESSION_OPTS["cadata"] = ca_certificate
