import json
import os

from libs.distro import distro
from libs.pymuffet import muffet


def check_cmd(cmd):
    import shutil
    r = shutil.which(cmd)
    return r is not None

class Filter(muffet.ScanFilter):
    def is_target(self, file: muffet.TFile):
        return file.extension == 'json'


class ProfileNotFoundError(Exception):
    pass


class LinuxPD:


    def __init__(self, osa, common_data_dir):
        self.profile = None
        self.os_profiles = []
        self.data_dir = f'{common_data_dir}/linux-pd/'
        self.osa = osa
        self.loadProfiles(self.data_dir)


    def loadProfiles(self, data_dir):
        conf = muffet.MuffetConf()
        conf.input = self.data_dir

        m = muffet.Muffet(conf)
        m.scan(Filter())

        for r in m.scanResults:
            d = self.osa.files.read_str(r.path)
            try:
                j = json.loads(d)
                self.os_profiles.append(j)

            except json.JSONDecodeError as e:
                self.osa.log.error(f"Invalid JSON in profile {r.path}: {e}")
                continue  # Пропустить поврежденный файл

        os_id = distro.id()
        os_version = distro.version()

        if os_id == "":
            # ! ! !
            # try detect...
            v = os.environ.get("TERMUX_VERSION")

            if v:
                os_id = 'termux'
                os_version = v


        r = []
        for p in self.os_profiles:
            a = p.get('id').lower()
            if a == os_id.lower():
                r.append(p)

        # if len(r) == 0:
        #     self.osa.log.w(f"id {os_id} - version {os_version} - arch {platform.machine()}")
        #     self.osa.log.f("Not found profile for your system distro!!")

        if not r:  # Более питонический способ проверить пустой список
            self.osa.log.error(f"No profiles found for distro: {os_id}")
            raise ProfileNotFoundError(f"Distribution {os_id} not supported")

        set_profile = r[0] if r else None
        if not set_profile:
            raise ValueError("No profile selected")

        self.profile = set_profile
