from enum import Enum

from CommonServerPython import *

RESULT = 'Result'
TACTIC = 'Tactic'


class Result(Enum):
    SUSPICIOUS = 'Suspicious'
    NOT_DETECTED = 'Not Detected'


RESULT_TO_COLOR = {
    Result.SUSPICIOUS: "🔴",
    Result.NOT_DETECTED: "🟢",
}


class Finding:
    tactic: str
    result: Result

    def __init__(self, context_name: str, value: dict):
        self.context_name = context_name
        self.tactic = value.get(TACTIC, f'{self.context_name} (missing tactic value)')
        self.result = Result(value.get(RESULT, Result.NOT_DETECTED.value))

    def to_summary_line(self) -> Dict[str, str]:
        return {
            TACTIC: self.tactic,
            RESULT: f'{RESULT_TO_COLOR[self.result]}  {self.result.value.title()}'
        }


def get_findings(malware_findings_context: dict) -> List[Finding]:
    findings = []
    for name, value in malware_findings_context.items():
        if isinstance(value, list):  # when running the script for the second time, values are put in lists.
            value = value[-1]  # solves for one or multiple values
        findings.append(Finding(name, value))
    return findings


def findings_to_command_results(findings: List[Finding]) -> CommandResults:
    if not findings:
        return CommandResults(
            readable_output='### Waiting on entries\n'
                            'When `InvestigationSummaryParse` is finished, its results will appear here.'
        )
    outputs = list(finding.to_summary_line() for finding in findings)
    return CommandResults(
        outputs_prefix='InvestigationSummary',
        outputs=outputs,
        readable_output=tableToMarkdown(
            '',
            outputs,
            [TACTIC, RESULT],
        )
    )


def main():
    try:
        malware_context = json.loads(
            demisto.incident().get('CustomFields', {}).get('malwareinvestigationsummary', '{}')
        )
        return_results(findings_to_command_results(get_findings(malware_context)))
    except Exception as e:
        demisto.error(traceback.format_exc())  # print the traceback
        return_error(f'Failed to execute InvestigationSummaryToTable. Error: {str(e)}')


if __name__ in ['__main__', '__builtin__', 'builtins']:
    main()
