import os
from typing import cast

from zscams.agent.src.support.cli import prompt_auth_info

from .client import backend_client
from zscams.agent.src.support.filesystem import resolve_path
from zscams.agent.src.support.configuration import config, CONFIG_PATH, ROOT_PATH
from zscams.agent.src.core.backend.client import BackendClient
from zscams.agent.src.support.logger import get_logger
from zscams.agent.src.support.os import remove_service

logger = get_logger("Unbootstrap")


def unbootstrap():
    if not backend_client.is_authenticated():
        username, totp = prompt_auth_info()
        backend_client.login(username, totp)

    backend_client.unbootstrap()
    logger.info(
        "Unbootstrapped from backend and revoked the certificate.",
    )

    remove_local_data()


def remove_local_data():
    remote_configs = config.get("remote", default={}, valtyp=dict)
    private_key_path = cast(
        str,
        resolve_path(remote_configs.get("client_key"), os.path.dirname(CONFIG_PATH)),
    )

    cert_path = cast(
        str,
        resolve_path(remote_configs.get("client_key"), os.path.dirname(CONFIG_PATH)),
    )

    ca_chain_path = cast(
        str,
        resolve_path(remote_configs.get("client_key"), os.path.dirname(CONFIG_PATH)),
    )

    cache_path = os.path.join(
        ROOT_PATH.parent,
        config.get("bootstrap.cache_dir", must_resolve=True, valtyp=str),
        BackendClient.MACHINE_INFO_FILE_NAME,
    )

    if os.path.exists(private_key_path):
        os.remove(private_key_path)
        logger.debug("Removed private key")

    if os.path.exists(cert_path):
        os.remove(cert_path)
        logger.debug("Removed certificate")

    if os.path.exists(ca_chain_path):
        os.remove(ca_chain_path)
        logger.debug("Removed CA Chain")

    if os.path.exists(cache_path):
        os.remove(cache_path)
        logger.debug("Removed Machine info")

    removed_service = remove_service("zscams")
    if removed_service:
        logger.debug("Removed ZSCAMs service")
