# Package contains functions that interact with Aurora SDK

import subprocess
import sys
from typing import Dict, List


CONAN_EXEC_NAME = "conan-with-aurora-profile"
KNOWN_ARCHITECTURES = ("aarch64", "armv7hl", "x86_64")
HOST_ARCH = "x86_64"


def check_sb2() -> bool:
    result = subprocess.run(["which", "sb2-config"], capture_output=True)
    return result.returncode == 0


def find_targets(known_archs: List[str] = KNOWN_ARCHITECTURES) -> Dict[str, str]:
    result = subprocess.run(["sb2-config", "-f"], capture_output=True)
    lines = result.stdout.decode("utf-8").splitlines()
    targets = {}
    for line in lines:
        for arch in known_archs:
            if line.endswith(arch):
                print(f"Found {line} target for {arch} architecture")
                targets[arch] = line
    return targets


def filter_targets(targets: Dict[str, str], target_names: List[str]) -> Dict[str, str]:
    if len(target_names) == 0:
        return targets
    new_targets = {}
    for arch in targets:
        found = False
        for name in target_names:
            if name in targets[arch]:
                found = True
                break
        if found:
            new_targets[arch] = targets[arch]
    return new_targets


def pick_target(targets: Dict[str, str]) -> str:
    if HOST_ARCH in targets:
        return targets[HOST_ARCH]
    return next(iter(targets.values()))


def run_conan_command(
    action: str,
    target: str,
    arguments: List[str],
    show_error: bool = True,
) -> bool:
    print(f"Executing {action} in {target}")
    try:
        subprocess.run(
            [*target_prefix(target), CONAN_EXEC_NAME, *arguments],
            check=True,
        )
    except subprocess.CalledProcessError as error:
        if show_error:
            print(f"Could not {action} in {target}", file=sys.stderr)
            print(error.output, file=sys.stderr)
        return False
    return True


def target_prefix(target: str) -> List[str]:
    return ["sb2", "-t", target]
