import json
from typing import List, Optional, Callable, Any, Tuple, Set
import pytest
from pytest_steps import test_steps
from copy import deepcopy

import pwndoc_api
from template_manager import PwndocTemplateManager
from helpers.db_models import DbTemplate, DbPwndocMapping
from tests.conftest import TMP_PATH, PWNDOC_DANGER_OVERRIDE
from tests.test_findings_parsing import test_connectivity
from tests.test_templating import delete_templates, upload_single_random_template_though_importer
from tests.test_finding_grouping import FindingHelper
import config
from loguru import logger


@pytest.mark.skipif(not PWNDOC_DANGER_OVERRIDE, reason="PWNDOC_DANGER_OVERRIDE must be allowed to enable testing of interaction with PwnDoc")
@pytest.mark.dependency(depends=["test_connectivity"])
class TestDB:
    def test_no_duplicate_version_creation(self, client):
        delete_templates(client)

        # todo: Currently there is a bug where both scan2report and pwndoc templates are saved in DB.

        fid = "burp_test_for_db_duplicates1"

        input_fids = {fid}

        with client.application.app_context():
            assert DbTemplate.get_template(fid, 'og') is None

            input_partial_fids = FindingHelper.full_fids_to_partial_fids(input_fids)
            FindingHelper.run_evaluation(client, "check_version_is_single", input_partial_fids, input_fids)

            version_history = DbTemplate.get_history(fid=fid, locale='og')
            assert len(version_history) == 1, "We've imported a new finding, it should only create one version in DB."

    def test_template_deleted_in_pwndoc_deletes_also_in_importer_db(self, client):
        template = upload_single_random_template_though_importer(client)
        fid, locale = template.fid, template.locale

        with client.application.app_context():
            assert DbTemplate.get_template(fid, locale)

            pwndoc_api.delete_all_templates_in_pwndoc()
            PwndocTemplateManager.update_template_db_from_pwndoc()

            assert DbTemplate.get_template(fid, locale) is None
