from typing import List

from sator_core.models.vulnerability import VulnerabilityLocator, VulnerabilityAttributes

from sator_core.ports.driven.persistence.storage import StoragePersistencePort
from sator_core.ports.driven.repositories.product import ProductRepositoryPort
from sator_core.ports.driving.analysis.attributes.vulnerability import VulnerabilityAttributesAnalysisPort


class VulnerabilityAttributesAnalysis(VulnerabilityAttributesAnalysisPort):
    def __init__(self, prod_repos: List[ProductRepositoryPort], storage_port: StoragePersistencePort):
        self.storage_port = storage_port
        self.product_repositories = prod_repos

    def analyze_vulnerability_attributes(self, vulnerability_id: str) -> VulnerabilityLocator | None:
        locator = self.storage_port.load(VulnerabilityLocator, vulnerability_id)

        if locator:
            return locator

        attributes = self.storage_port.load(VulnerabilityAttributes, vulnerability_id)

        if attributes and attributes.configuration:
            for product_repo in self.product_repositories:
                # TODO: updated to cover multiple configurations
                config = product_repo.search_config_by_str(attributes.configuration)
                # TODO: extract function/file from component

                if config:
                    locator = VulnerabilityLocator(
                        product=config.product, version=config.version, function=None, file=None
                    )

                    self.storage_port.save(locator, vulnerability_id)
                    return locator

        return None
