from intelligence.base import *
import requests
import json
import base64


URL = "https://loaderinsight.agency/api/"


class LoaderInsightAgence(OnlineChecker):

    name = "LoaderInsightAgency"
    options = {
        "key": ("", "LIA API key"),
    }

    def __session(self):
        session = self.preconfigured_session()  # automatically set options such as timeout or ssl_verify
        key = self.options.get("key")
        if not key:
            raise KeyError("No API key")
        session.headers.update({'accept': 'application/json', 'Authorization': key})
        return session
    
    def check(self, analysis):
        detections = { }
        session = self.__session()
        response = session.post(f"{URL}?ep=sha256", data={"sha256": analysis.entropy.sha256}, headers={'Content-Type': 'application/x-www-form-urlencoded'})
        if response.ok and response.content:
            data = response.json()
            print(json.dumps(data, indent=4))
            if "message" in data and data["message"] != "ok":
                raise ValueError(data["message"])
            if "results" in data:
                res = data["results"]
                by_bot = {}
                for t in res.get("tasks", []):
                    family = t.get("family", "unknown_family")
                    l = by_bot.setdefault(family, [])
                    l.append(t)
                static_det = " + ".join(res.get("static_detection", []))
                sandbox_det = " + ".join(res.get("sandbox_detections", []))
                for k, v in by_bot.items():
                    txt = f"Seen in {len(v)} tasks"
                    if static_det:
                        txt += f" (static det: {static_det})"
                    if sandbox_det:
                        txt += f" (sandbox det: {sandbox_det})"
                    detections[f"Distributed by {k}"] = OnlineDetection(DetectionLevel.MALWARE, txt)
            if not detections:
                return None
        elif response.status_code == 404:
            return None
        else:
            response.raise_for_status()
            return None

        url = "https://loaderinsight.agency/?p=payload_view&hash={}".format(analysis.entropy.sha256)
        return OnlineResult(detections=detections, url=url)


    def download(self, query):
        session = self.__session()
        if len(query) != 64:
            return None
        response = session.post(f"{URL}?ep=download", data={"sha256": query}, headers={'Content-Type': 'application/x-www-form-urlencoded'})
        if response.ok:
            if len(response.content) < 1024 and b"\"message\"" in response.content:
                return None
            return OnlineFile(url=f"", content=response.content)
        elif response.status_code in (404,):
            return None
        else:
            response.raise_for_status()
            return None
