from sigma.pipelines.common import (
    logsource_windows_file_access,
    logsource_windows_file_change,
    logsource_windows_file_delete,
    logsource_windows_file_event,
    logsource_windows_file_rename,
    logsource_windows_network_connection,
    logsource_windows_process_creation,
    logsource_windows_registry_add,
    logsource_windows_registry_delete,
    logsource_windows_registry_event,
    logsource_windows_registry_set,
)
from sigma.pipelines.kusto_common.schema import FieldMappings

# from .schema import MicrosoftXDRFieldMappings
from .tables import SENTINEL_ASIM_TABLES

# Get table names from the tables.py file
table_names = list(SENTINEL_ASIM_TABLES.keys())


# Rule Categories -> Query Table Names
# Use the table names from the tables.py file by looking for relevant terms in the table names
CATEGORY_TO_TABLE_MAPPINGS = {
    "process_creation": next((table for table in table_names if "process" in table.lower()), "imProcessCreate"),
    # "image_load": next((table for table in table_names if 'image' in table.lower()), None),
    "file_access": next((table for table in table_names if "file" in table.lower()), "imFileEvent"),
    "file_change": next((table for table in table_names if "file" in table.lower()), "imFileEvent"),
    "file_delete": next((table for table in table_names if "file" in table.lower()), "imFileEvent"),
    "file_event": next((table for table in table_names if "file" in table.lower()), "imFileEvent"),
    "file_rename": next((table for table in table_names if "file" in table.lower()), "imFileEvent"),
    "registry_add": next((table for table in table_names if "registry" in table.lower()), "imRegistry"),
    "registry_delete": next((table for table in table_names if "registry" in table.lower()), "imRegistry"),
    "registry_event": next((table for table in table_names if "registry" in table.lower()), "imRegistry"),
    "registry_set": next((table for table in table_names if "registry" in table.lower()), "imRegistry"),
    "network_connection": next((table for table in table_names if "network" in table.lower()), "imNetworkSession"),
    "proxy": next((table for table in table_names if "web" in table.lower()), "imWebSession"),
    "webserver": next((table for table in table_names if "web" in table.lower()), "imWebSession"),
}

## Rule Categories -> RuleConditions
CATEGORY_TO_CONDITIONS_MAPPINGS = {
    "process_creation": logsource_windows_process_creation(),
    # "image_load": logsource_windows_image_load(),
    "file_access": logsource_windows_file_access(),
    "file_change": logsource_windows_file_change(),
    "file_delete": logsource_windows_file_delete(),
    "file_event": logsource_windows_file_event(),
    "file_rename": logsource_windows_file_rename(),
    "registry_add": logsource_windows_registry_add(),
    "registry_delete": logsource_windows_registry_delete(),
    "registry_event": logsource_windows_registry_event(),
    "registry_set": logsource_windows_registry_set(),
    "network_connection": logsource_windows_network_connection(),
}


class SentinelASIMFieldMappings(FieldMappings):
    pass


SENTINEL_ASIM_FIELD_MAPPINGS = SentinelASIMFieldMappings(
    table_mappings={
        "imAuditEvent": {
            "CommandLine": "Operation",
            "User": "ActorUsername",
            "TargetFilename": "Object",
            "Image": "ActingAppName",
            "SourceIP": "SrcIpAddr",
            "DestinationIP": "TargetIpAddr",
            "DestinationHostname": "TargetHostname",
            "EventType": "EventType",
            "TargetObject": "Object",
            "NewValue": "NewValue",
            "OldValue": "OldValue",
            "type": "ObjectType",
            "SourceHostname": "SrcHostname",
            "TargetUsername": "TargetUsername",
            "ProcessName": "ActingAppName",
            "ProcessId": "ActingAppId",
            "LogonId": "ActorSessionId",
            "TargetLogonId": "TargetSessionId",
            "SubjectUserName": "ActorUsername",
            "ObjectName": "Object",
            "ObjectType": "ObjectType",
            "NewProcessName": "ActingAppName",
            "Status": "EventResultDetails",
            "IpAddress": ["SrcIpAddr", "TargetIpAddr"],
            "SourcePort": "SrcPortNumber",
            "DestinationPort": "TargetPortNumber",
            "Protocol": "LogonProtocol",
        },
        "imAuthentication": {
            "User": ["ActorUsername", "TargetUsername"],  # Alias field, can map to either
            "SourceHostname": "SrcHostname",
            "DestinationHostname": "TargetHostname",
            "SourceIP": "SrcIpAddr",
            "DestinationIP": "TargetIpAddr",
            "SourcePort": "SrcPortNumber",
            "DestinationPort": "TargetPortNumber",
            "Status": "EventResultDetails",
            "IpAddress": ["SrcIpAddr", "TargetIpAddr"],  # Can map to either source or target IP
            "SubjectUserName": "ActorUsername",
            "WorkstationName": "SrcHostname",  # This is an approximation
            "ComputerName": ["SrcHostname", "TargetHostname"],  # Can map to either source or target hostname
            "AuthenticationPackageName": "LogonProtocol",
            "LogonProcessName": "LogonMethod",
            "TargetUserSid": "TargetUserId",
            "TargetDomainName": "TargetDomain",
            "TargetOutboundDomainName": "TargetDomain",
            "ElevatedToken": "EventType",  # This could map to "Elevate" in EventType
            "TargetUserPrincipalName": "TargetUsername",  # This is an approximation
            "SubjectDomainName": "ActorScope",
            "SubjectUserSid": "ActorUserId",
            "SubjectLogonId": "ActorSessionId",
            "IpPort": ["SrcPortNumber", "TargetPortNumber"],  # Can map to either source or target port
            "LmPackageName": "LogonProtocol",  # This is an approximation
            "userAgent": "HttpUserAgent",
            # Common fields with specific relevance to this table
            "DvcHostname": ["SrcHostname", "TargetHostname"],  # Can map to either source or target hostname
            "DvcIpAddr": ["SrcIpAddr", "TargetIpAddr"],  # Can map to either source or target IP
            "DvcDomain": ["SrcDomain", "TargetDomain"],  # Can map to either source or target domain
            "DvcDomainType": ["SrcDomainType", "TargetDomainType"],  # Can map to either source or target domain type
            "DvcFQDN": ["SrcFQDN", "TargetFQDN"],  # Can map to either source or target FQDN
            "DvcId": ["SrcDvcId", "TargetDvcId"],  # Can map to either source or target device ID
            "DvcIdType": ["SrcDvcIdType", "TargetDvcIdType"],  # Can map to either source or target device ID type
            "DvcDescription": ["SrcDescription", "TargetDescription"],  # Can map to either source or target description
            "DvcOs": ["SrcDvcOs", "TargetDvcOs"],  # Can map to either source or target OS
        },
        "_Im_Dns": {
            "SourceIP": "SrcIpAddr",
            "DestinationIP": "DstIpAddr",
            "SourceHostname": "SrcHostname",
            "DestinationHostname": "DstHostname",
            "SourcePort": "SrcPortNumber",
            "DestinationPort": "DstPortNumber",
            "IpAddress": ["SrcIpAddr", "DstIpAddr"],  # Can map to either source or target IP
            "ProcessName": "SrcProcessName",
            "ProcessId": "SrcProcessId",
            "User": "SrcUsername",
            "ComputerName": ["SrcHostname", "DstHostname"],  # Can map to either source or target hostname
            "Image": "SrcProcessName",
            "QueryName": "DnsQuery",
            "QueryStatus": "EventResultDetails",
            "QueryResults": "DnsResponseName",
            "Protocol": "NetworkProtocol",
            "c-useragent": "HttpUserAgent",
            "userAgent": "HttpUserAgent",
            "Category": "UrlCategory",
            "Status": "EventResultDetails",
            "Product": "EventProduct",
            "Company": "EventVendor",
        },
        "imFileEvent": {
            "SourceIP": "SrcIpAddr",
            "DestinationIP": "DstIpAddr",
            "SourceHostname": "SrcHostname",
            "DestinationHostname": "DstHostname",
            "SourcePort": "SrcPortNumber",
            "User": "ActorUsername",
            "TargetFilename": "TargetFileName",
            "Image": "TargetFilePath",
            "ParentImage": "ActingProcessName",
            "CommandLine": "ActingProcessCommandLine",
            "ParentCommandLine": "ActingProcessCommandLine",
            "ProcessName": "ActingProcessName",
            "ProcessId": "ActingProcessId",
            "ParentProcessName": "ActingProcessName",
            "ParentProcessId": "ActingProcessId",
            "LogonId": "ActorSessionId",
            "TargetObject": "TargetFilePath",
            "Details": "TargetFilePath",
            "SubjectUserName": "ActorUsername",
            "ObjectName": "TargetFilePath",
            "OldFilePath": "SrcFilePath",
            "NewFilePath": "TargetFilePath",
            "OldFileName": "SrcFileName",
            "NewFileName": "TargetFileName",
            "c-uri": "TargetUrl",
            "c-useragent": "HttpUserAgent",
            "cs-method": "NetworkApplicationProtocol",
            "userAgent": "HttpUserAgent",
            "Category": "ThreatCategory",
            "OperationName": "EventType",
            "ProcessGuid": "ActingProcessGuid",
            "CreationUtcTime": "TargetFileCreationTime",
        },
        "imNetworkSession": {
            "SourceIP": "SrcIpAddr",
            "DestinationIP": "DstIpAddr",
            "DestinationIp": "DstIpAddr",
            "SourceHostname": "SrcHostname",
            "DestinationHostname": "DstHostname",
            "SourcePort": "SrcPortNumber",
            "DestinationPort": "DstPortNumber",
            "SourceMAC": "SrcMacAddr",
            "DestinationMAC": "DstMacAddr",
            "Protocol": "NetworkProtocol",
            "NetworkProtocol": "NetworkApplicationProtocol",
            "User": ["SrcUsername", "DstUsername"],
            "Image": ["SrcProcessName", "DstProcessName"],
            "ProcessName": ["SrcProcessName", "DstProcessName"],
            "ProcessId": ["SrcProcessId", "DstProcessId"],
            "ProcessGuid": ["SrcProcessGuid", "DstProcessGuid"],
            "LogonId": ["SrcUserId", "DstUserId"],
            "SourceUserName": "SrcUsername",
            "DestinationUserName": "DstUsername",
            "SourceImage": "SrcProcessName",
            "DestinationImage": "DstProcessName",
            "SourceProcessGUID": "SrcProcessGuid",
            "DestinationProcessGUID": "DstProcessGuid",
            "SourceProcessId": "SrcProcessId",
            "DestinationProcessId": "DstProcessId",
            "SourceThreadId": "SrcProcessId",
            "DestinationThreadId": "DstProcessId",
            "SourceIsIpv6": "NetworkProtocolVersion",
            "DestinationIsIpv6": "NetworkProtocolVersion",
            "Initiated": "NetworkDirection",
            "SourcePortName": "SrcAppName",
            "DestinationPortName": "DstAppName",
            "State": "EventSubType",
            "IpProtocol": "NetworkProtocol",
            "BytesReceived": "DstBytes",
            "BytesSent": "SrcBytes",
            "PacketsReceived": "DstPackets",
            "PacketsSent": "SrcPackets",
            "c-uri": "TargetUrl",
            "c-useragent": "HttpUserAgent",
            "cs-method": "NetworkApplicationProtocol",
            "cs-version": "NetworkProtocolVersion",
            "cs-Cookie": "HttpUserAgent",
            "cs-Referrer": "HttpUserAgent",
            "sc-status": "EventResultDetails",
            "userAgent": "HttpUserAgent",
            "Category": "ThreatCategory",
            "OperationName": "EventType",
            "Action": "DvcAction",
            "RuleName": "NetworkRuleName",
        },
        "imProcessCreate": {  # process_creation, Sysmon EventID 1 -> imProcessCreate table
            "Image": "TargetProcessName",
            "ParentImage": ["ParentProcessName", "ActingProcessName"],
            "CommandLine": "TargetProcessCommandLine",
            "ParentCommandLine": "ActingProcessCommandLine",
            "User": "TargetUsername",
            "LogonGuid": "TargetUserSessionGuid",
            "LogonId": "TargetUserSessionId",
            "SourceImage": "ActingProcessName",
            "TargetImage": "TargetProcessName",
            "SourceUser": "ActorUsername",
            "TargetUser": "TargetUsername",
            "SourceProcessId": "ActingProcessId",
            "TargetProcessId": "TargetProcessId",
            "SourceProcessGUID": "ActingProcessGuid",
            "TargetProcessGUID": "TargetProcessGuid",
            "ProcessId": "TargetProcessId",
            "ProcessGuid": "TargetProcessGuid",
            "ParentProcessId": ["ParentProcessId", "ActingProcessId"],
            "ParentProcessGuid": ["ParentProcessGuid", "ActingProcessGuid"],
            "ParentUser": "ActorUsername",
            "IntegrityLevel": "TargetProcessIntegrityLevel",
            "ParentProcessName": "ParentProcessName",
            "CurrentDirectory": "TargetProcessCurrentDirectory",
            "OriginalFileName": ["TargetProcessFileOriginalName", "TargetProcessFilename"],
            "Description": "TargetProcessFileDescription",
            "Product": "TargetProcessFileProduct",
            "Company": "TargetProcessFileCompany",
            "FileVersion": "TargetProcessFileVersion",
            "GrantedAccess": "TargetProcessTokenElevation",
            "CallTrace": "TargetProcessInjectedAddress",
            "ParentIntegrityLevel": "ParentProcessIntegrityLevel",
            "TerminalSessionId": "TargetUserSessionId",
            "sha1": "TargetProcessSHA1",
            "sha256": "TargetProcessSHA256",
            "md5": "TargetProcessMD5",
            "ProcessVersionInfoOriginalFileName": "TargetProcessFileVersion",
            "ProcessVersionInfoFileDescription": "TargetProcessFileDescription",
            "ProcessIntegrityLevel": "TargetProcessIntegrityLevel",
            "InitiatingProcessFolderPath": "ActingProcessName",
            "InitiatingProcessCommandLine": "ActingProcessCommandLine",
        },
        "imRegistry": {
            "Image": "ActingProcessName",
            "ParentImage": "ParentProcessName",
            "User": "ActorUsername",
            "TargetObject": "RegistryKey",
            "Details": "RegistryValueData",
            "EventType": "EventType",
            "ProcessId": "ActingProcessId",
            "ProcessGuid": "ActingProcessGuid",
            "ParentProcessId": "ParentProcessId",
            "ParentProcessGuid": "ParentProcessGuid",
            "ObjectName": "RegistryKey",
            "ObjectValueName": "RegistryValue",
            "ObjectType": "RegistryValueType",
            "ObjectValue": "RegistryValueData",
            "OldName": "RegistryPreviousKey",
            "NewName": "RegistryKey",
            "OldValueType": "RegistryPreviousValueType",
            "NewValueType": "RegistryValueType",
            "OldValue": "RegistryPreviousValueData",
            "NewValue": "RegistryValueData",
            "ProcessName": "ActingProcessName",
            "SubjectUserName": "ActorUsername",
            "SubjectUserSid": "ActorUserId",
            "SubjectDomainName": "ActorScope",
            "SubjectLogonId": "ActorSessionId",
        },
        "imWebSession": {
            "c-uri": "Url",
            "c-uri-query": "Url",
            "c-useragent": "HttpUserAgent",
            "cs-method": "HttpRequestMethod",
            "cs-version": "HttpVersion",
            "cs-host": "HttpHost",
            "cs-Referrer": "HttpReferrer",
            "sc-status": "HttpStatusCode",
            "cs-User-Agent": "HttpUserAgent",
            "r-dns": "HttpHost",
            "request": "Url",
            "request_body": "Url",
            "request_method": "HttpRequestMethod",
            "request_url": "Url",
            "request_url_query": "Url",
            "response_status_code": "HttpStatusCode",
            "url_category": "UrlCategory",
            "url_original": "UrlOriginal",
            "http_request_time": "HttpRequestTime",
            "http_response_time": "HttpResponseTime",
            "http_content_type": "HttpContentType",
            "http_user_agent": "HttpUserAgent",
            "http_referrer": "HttpReferrer",
            "x_forwarded_for": "HttpRequestXff",
            "file_name": "FileName",
            "file_hash": ["FileMD5", "FileSHA1", "FileSHA256", "FileSHA512"],
            "file_size": "FileSize",
            "file_type": "FileContentType",
        },
    },
    generic_mappings={
        "EventID": "EventOriginalType",
        "EventType": "EventType",
        "Product": "EventProduct",
        "Vendor": "EventVendor",
        "DeviceName": "DvcHostname",
        "DeviceHostname": "DvcHostname",
        "Computer": "DvcHostname",
        "Hostname": "DvcHostname",
        "IpAddress": "DvcIpAddr",
        "SourceSystem": "EventProduct",
        "TimeGenerated": "EventStartTime",
    },
)
