import json
import sys

from libs.spk_v.SpkRepo import SPK_Repo
from libs.osaf.k_osa import kOSA
from libs.pyconf import pyconf
from libs.pyfap import fap
from libs.spider_logger.logger import SpiderLog
from libs.spk_v import commands
from libs.spk_v.api import SPK5_API
from libs.spk_v.tkmg import VTaskManager, VRunnable


class TestPayload(VRunnable):
    def run(self):
        print("aaaa hello@!")




class SysPackVCore:


    def create_platform_filters(self, osa):

        pf = {}
        # print(osa.platform_info.profile)
        pf['os.family'] = osa.conf.get('os_conf').get('os_family')
        pf['arch'] = osa.utils.arch_normalize(osa.conf.get("os_conf").get('os_arch'))
        pf['pkg'] = osa.platform_info.profile.get("backend_pkgman")
        return pf


    def __init__(self, env, log : SpiderLog, kosa : kOSA):
        self.APP_VERSION = "0.2"
        self.APP_NAME = "SysPack-V"
        self.APP_ID = "org.pr-automata.syspack"
        self.APP_AUTHOR = "Java86, Alina86"
        self.APP_DESC = "Software for delivery, running, installing scripts and software."
        self.env = env
        self.log = log
        self.kosa = kosa

        self.osa = kosa.get_osa(log, env.app_dir, pyconf.read(f'{self.env.etc}/osaf/conf.json'))

        self.conf = pyconf.read(f'{self.env.etc}/syspack/conf.json')

        if self.conf.get('repo').get('use_platform_filters'):
            self.filters = self.create_platform_filters(self.osa)
        else:
            self.filters = {}

        self.log.d(self.filters)
        self.spk_initial()

        self.runtime = None
        self.repository = SPK_Repo(
            self.log,
            self.osa,
            pyconf.read(f'{self.env.etc}/unirepo/conf.json'),
            pyconf.read(f'{self.env.etc}/unirepo/sources.json'), self
        )
        self.api = SPK5_API(self)
        self.cli = fap.FAP()
        self.task_manager = VTaskManager(self.osa)

        self.log.w("⚠️ This is unsable SysPack-V Release!")

    def run_app(self):
        commands.spk_reg_all(self.cli, self)
        self.cli.now(sys.argv[0:])
        self.task_manager.run_tasks(self)

    def spk_initial(self):
        cdd = self.env.data + '/spk-v/'
        of = self.osa.files
        id_f = cdd + "id.json"
        if not of.exists(cdd):
            of.mkdir(cdd)
            id_d = {}
            of.write_str(id_f ,json.dumps(id_d))


