import time
from dataclasses import dataclass, field
from secator.output_types import OutputType
from secator.utils import rich_to_ansi, rich_escape as _s
from secator.definitions import MATCHED_AT, NAME, ID, EXTRA_DATA, REFERENCE


@dataclass
class Exploit(OutputType):
	name: str
	provider: str
	id: str
	matched_at: str = ''
	ip: str = ''
	confidence: str = 'low'
	cvss_score: float = 0
	reference: str = ''
	cves: list = field(default_factory=list, compare=False)
	tags: list = field(default_factory=list, compare=False)
	extra_data: dict = field(default_factory=dict, compare=False)
	_source: str = field(default='', repr=True)
	_type: str = field(default='exploit', repr=True)
	_timestamp: int = field(default_factory=lambda: time.time(), compare=False)
	_uuid: str = field(default='', repr=True, compare=False)
	_context: dict = field(default_factory=dict, repr=True, compare=False)
	_tagged: bool = field(default=False, repr=True, compare=False)
	_duplicate: bool = field(default=False, repr=True, compare=False)
	_related: list = field(default_factory=list, compare=False)

	_table_fields = [
		MATCHED_AT,
		NAME,
		ID,
		EXTRA_DATA,
		REFERENCE
	]
	_sort_by = ('matched_at', 'name')

	def __str__(self):
		return self.name

	def __repr__(self):
		s = rf'[bold red]⍼[/]  \[[bold red]{self.name}'
		if self.reference:
			s += f' [link={_s(self.reference)}]🡕[/link]'
		s += '[/]]'
		if self.matched_at:
			s += f' {_s(self.matched_at)}'
		if self.tags:
			tags_str = ', '.join(self.tags)
			s += rf' \[[cyan]{tags_str}[/]]'
		if self.extra_data:
			data = ', '.join([f'{k}:{v}' for k, v in self.extra_data.items()])
			s += rf' \[[yellow]{_s(str(data))}[/]]'
		if self.confidence == 'low':
			s = f'[dim]{s}[/]'
		return rich_to_ansi(s)
