from __future__ import annotations

import hashlib
from typing import TYPE_CHECKING

from dissect.target.plugins.os.windows import certlog
from dissect.target.target import Target
from tests._utils import absolute_path

if TYPE_CHECKING:
    from dissect.target.filesystem import VirtualFilesystem


def test_certlog_plugin(target_win: Target, fs_win: VirtualFilesystem) -> None:
    ca_edb = absolute_path("_data/plugins/os/windows/certlog/SEVENKINGDOMS-CA.edb")

    fs_win.map_file("Windows/System32/Certlog/SEVENKINGDOMS-CA.edb", ca_edb)

    target_win.add_plugin(certlog.CertLogPlugin)
    assert len(list(target_win.certlog())) == 142
    assert len(list(target_win.certlog.requests())) == 11
    assert len(list(target_win.certlog.request_attributes())) == 26
    assert len(list(target_win.certlog.crls())) == 2
    certificates = list(target_win.certlog.certificates())
    assert len(certificates) == 11
    assert len(list(target_win.certlog.certificate_extensions())) == 92
    assert certificates[0].serial_number == 23146941333149199441888068127529844838
    assert certificates[0].serial_number_hex == "1169f0517d9b598e4ba7af46e4674066"
    assert certificates[0].fingerprint.sha1 == hashlib.sha1(certificates[0].raw_certificate).hexdigest()
    assert certificates[0].fingerprint.sha1 == "061ec97dcef82d0e2d100b590e790a803d4573ae"


def test_certlog_plugin_direct() -> None:
    ca_edb = absolute_path("_data/plugins/os/windows/certlog/SEVENKINGDOMS-CA.edb")

    target = Target.open_direct([ca_edb])
    assert len(list(target.certlog())) == 142
    assert len(list(target.certlog.requests())) == 11
    assert len(list(target.certlog.request_attributes())) == 26
    assert len(list(target.certlog.crls())) == 2
    assert len(list(target.certlog.certificates())) == 11
    assert len(list(target.certlog.certificate_extensions())) == 92
