from .imports import *
def _should_use_remote(**kwargs) -> bool:
    """
    Only use remote mode IF:
    - user_at_host is provided
    - AND password/key is provided
    Otherwise: local write.
    """
    user = kwargs.get("user_at_host")
    if not user:
        return False  # not remote

    # If user_at_host is provided, then password or key MUST be present
    if kwargs.get("password") or kwargs.get("key"):
        return True

    return False  # user provided but no auth → treat as local


def _write_to_file(contents: str, file_path: str, **kwargs) -> str:
    """
    Universal safe writer for any file content.
    Works locally and remotely without breaking quotes.
    """

    # --- Decode mode selection ---
    remote = _should_use_remote(**kwargs)

    # Create directory path
    dirname = os.path.dirname(file_path)
    make_dirs(dirname, exist_ok=True, **kwargs)

    # Base64 encoding ensures zero escaping issues
    b64 = base64.b64encode(contents.encode("utf-8")).decode("utf-8")

    # Build decode + tee command
    cmd = (
        f"echo '{b64}' | base64 -d | "
        f"sudo tee {shlex.quote(file_path)} > /dev/null"
    )

    # --- Local write ---
    if not remote:
        return run_pruned_func(
            run_local_cmd,
            cmd=cmd,
            **kwargs
        )

    # --- Remote write ---
    return run_pruned_func(
        run_remote_cmd,
        user_at_host=kwargs["user_at_host"],
        cmd=cmd,
        **kwargs
    )


def write_to_file(*, contents: str, file_path: str, **kwargs):
    """
    Error-handled wrapper.
    """

    try:
        result = _write_to_file(contents=contents, file_path=file_path, **kwargs)
        return result

    except Exception as e:
        print("WRITE ERROR:", e)
        raise RuntimeError(f"Failed writing: {file_path}")
def check_if_default_dir(directory):
    
    default_files = [os.path.join(directory,'index.conf'),os.path.join(directory,'index_http.conf')]
    dir_list = collect_globs(directories=[directory], **kwargs)#,user_at_host='solcatcher',password=PASSWORD).get('files')
    
    if len(dir_list) == 2 and default_files[0] in dir_list and default_files[1] in dir_list:
        return True
    return False
