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


URL = "https://labs.inquest.net/api"


class InQuest(OnlineChecker):

    name = "InQuest"
    options = {
        "key": ("", "InQuest API key"),
    }
    
    def check(self, analysis):
        detections = { }
        key = self.options.get("key")
        if not key:
            raise KeyError("No API key")
        message = ""
        session = self.preconfigured_session()  # automatically set options such as timeout or ssl_verify
        session.headers.update({'accept': 'application/json'})
        session.headers.update({'Authorization': key})

        response = session.get(f"{URL}/dfi/search/hash/sha256", params={ "hash": analysis.entropy.sha256 })
        if response.ok:
            data = response.json()
            if "error" in data:
                raise ValueError(data["error"])
            data = data.get("data", [])
            if not data:
                return None
            for obj in data:
                verdict = obj.get("classification")
                if not verdict:
                    return None
                level = DetectionLevel.from_text(verdict)
                name = obj.get("last_inquest_featext", "???")
                iocs = obj.get('num_iocs', 0)
                score = obj.get('inquest_ml_score', 0) * 100
                sig = f"iocs: {iocs:d}  score: {score:.2f}"
                detections[name] = OnlineDetection(level, sig)
        elif response.status_code == 404:
            return None
        else:
            response.raise_for_status()
            return None

        url = f"https://labs.inquest.net/dfi/sha256/{analysis.entropy.sha256}"
        return OnlineResult(detections=detections, 
            url=url
        )

