import json
import unittest

from core.event_model import NormalizedEvent


class TestNormalizedEvent(unittest.TestCase):
    def test_defaults_and_serialization(self):
        event = NormalizedEvent(
            event_type="process_create",
            source="kernel",
            severity="info",
            hostname="WORKSTATION",
            user="Joey",
            pid=8420,
            parent_pid=1136,
            process_name="ollama.exe",
            path=r"C:\Program Files\Ollama\ollama.exe",
            command_line="ollama serve",
        )

        payload = event.to_dict()

        self.assertIn("event_id", payload)
        self.assertIn("timestamp", payload)
        self.assertEqual(payload["event_type"], "process_create")
        self.assertEqual(payload["source"], "kernel")
        self.assertEqual(payload["severity"], "info")
        self.assertEqual(payload["pid"], 8420)
        self.assertEqual(payload["parent_pid"], 1136)
        self.assertEqual(payload["process_name"], "ollama.exe")

        serialized = event.to_json()
        loaded = json.loads(serialized)
        self.assertEqual(loaded["event_id"], payload["event_id"])
        self.assertEqual(loaded["process_name"], "ollama.exe")

    def test_from_dict_round_trip(self):
        payload = {
            "event_type": "network_connect",
            "source": "collector",
            "severity": "medium",
            "confidence": 75,
            "hostname": "HOST-01",
            "user": "Joey",
            "pid": 4567,
            "process_name": "python.exe",
            "remote_ip": "203.0.113.10",
            "remote_port": 443,
            "domain": "example.com",
            "rule_id": "NET-001",
            "risk_score": 55,
            "tags": ["network", "suspicious"],
            "metadata": {"protocol": "TCP", "state": "ESTABLISHED"},
        }

        event = NormalizedEvent.from_dict(payload)
        round_trip = event.to_dict()

        self.assertEqual(round_trip["event_type"], "network_connect")
        self.assertEqual(round_trip["rule_id"], "NET-001")
        self.assertEqual(round_trip["tags"], ["network", "suspicious"])
        self.assertEqual(round_trip["metadata"]["protocol"], "TCP")
        self.assertEqual(round_trip["metadata"]["state"], "ESTABLISHED")

    def test_json_deserialization(self):
        raw = {
            "event_type": "file_write",
            "source": "kernel",
            "severity": "low",
            "pid": 100,
            "process_name": "cmd.exe",
            "path": r"C:\Windows\Temp\test.txt",
            "metadata": {"operation": "write"},
        }

        event = NormalizedEvent.from_json(json.dumps(raw))
        self.assertEqual(event.event_type, "file_write")
        self.assertEqual(event.path, r"C:\Windows\Temp\test.txt")
        self.assertEqual(event.metadata["operation"], "write")


if __name__ == "__main__":
    unittest.main()
