# -*- coding: utf_8 -*-
import logging
from pathlib import Path

from django.conf import settings

from mobsf.MobSF.utils import (
    append_scan_status,
    run_with_timeout,
    settings_enabled,
)

logger = logging.getLogger(__name__)


def apkid_analysis(checksum, apk_file):
    """APKID Analysis of DEX files."""
    if not settings_enabled('APKID_ENABLED'):
        return {}
    try:
        import apkid
    except ImportError as exp:
        msg = 'APKiD - Could not import APKiD'
        logger.error(msg)
        append_scan_status(checksum, msg, repr(exp))
        return {}

    apkid_ver = apkid.__version__
    from apkid.apkid import Scanner, Options
    from apkid.output import OutputFormatter
    from apkid.rules import RulesManager

    msg = f'Running APKiD {apkid_ver}'
    logger.info(msg)
    append_scan_status(checksum, msg)
    options = Options(
        timeout=30,
        verbose=False,
        entry_max_scan_size=settings.DATA_UPLOAD_MAX_MEMORY_SIZE,
        recursive=True,
    )
    output = OutputFormatter(
        json_output=True,
        output_dir=None,
        rules_manager=RulesManager(),
        include_types=False,
    )
    rules = options.rules_manager.load()
    scanner = Scanner(rules, options)
    findings = {}
    res = None
    try:
        res = run_with_timeout(
            scanner.scan_file,
            settings.BINARY_ANALYSIS_TIMEOUT,
            apk_file)
    except Exception as e:
        msg = 'APKID scan timed out'
        logger.error(msg)
        append_scan_status(
            checksum,
            msg,
            str(e))
    try:
        if res:
            findings = output._build_json_output(res)['files']
    except AttributeError:
        # apkid >= 2.0.3
        try:
            if res:
                findings = output.build_json_output(res)['files']
        except AttributeError:
            msg = (
                'yara-python dependency required by '
                'APKiD is not installed properly. '
                'Skipping APKiD analysis!')
            logger.error(msg)
            append_scan_status(
                checksum,
                msg,
                'Missing dependency')
    sanitized = {}
    for item in findings:
        filename = item['filename']
        if '!' in filename:
            filename = filename.split('!', 1)[1]
        else:
            filename = Path(filename).name
        sanitized[filename] = item['matches']
    return sanitized
