from pathlib import Path

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

from .client import backend_client
from zscams.agent.src.support.configuration import config, ROOT_PATH
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():
    custom_config_dir = Path(config.get("config_dir", must_resolve=True))

    cert_files_to_remove = [
        config.get("remote.client_key", must_resolve=True),
        config.get("remote.client_cert", must_resolve=True),
        config.get("remote.ca_chain", must_resolve=True),
    ]

    for cert_file in cert_files_to_remove:
        path = custom_config_dir.joinpath(cert_file)
        if path and path.exists():
            path.unlink()
            logger.debug(f"Removed {cert_file}")

    cache_path = ROOT_PATH.parent.joinpath(
        config.get("bootstrap.cache_dir", must_resolve=True),
        backend_client.MACHINE_INFO_FILENAME,
    )

    if cache_path.exists():
        cache_path.unlink()
        logger.debug("Removed Machine info")

    set_machine_id(None)

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