import json
import os
import tempfile
import unittest

from core.service_runtime import TelemetryRelayService


class TestTelemetryRelayService(unittest.TestCase):
    def test_service_loads_runtime_settings(self):
        service = TelemetryRelayService()
        self.assertTrue(service.enabled)
        self.assertGreater(service.poll_interval, 0)
        self.assertTrue(service.output_path.is_absolute() or str(service.output_path).startswith("C:"))

    def test_run_cycle_records_process_started_event(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            output_path = os.path.join(tmpdir, "relay.jsonl")
            service = TelemetryRelayService(output_path=output_path)
            previous = {}
            current = {1234: "ollama.exe"}

            events = service.run_cycle(previous, current)
            self.assertTrue(any(event["event"] == "process_started" for event in events))
            self.assertEqual("medium", events[0]["severity"])
            self.assertEqual("WATCHLISTED", events[0]["classification"])

            self.assertTrue(os.path.exists(output_path))
            with open(output_path, "r", encoding="utf-8") as handle:
                log_lines = [json.loads(line) for line in handle if line.strip()]
            self.assertTrue(any(item["event"] == "process_started" for item in log_lines))
            self.assertEqual(str(service.output_path), output_path)
            service.close()

    def test_run_cycle_records_process_exit_and_database_events(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            output_path = os.path.join(tmpdir, "relay.jsonl")
            db_path = os.path.join(tmpdir, "events.db")
            service = TelemetryRelayService(output_path=output_path, db_path=db_path)

            started = service.run_cycle({}, {1234: "worker.exe"})
            exited = service.run_cycle({1234: "worker.exe"}, {})

            self.assertEqual("process_started", started[0]["event"])
            self.assertEqual("process_exited", exited[0]["event"])
            stored_types = {event["event_type"] for event in service.database.list_events()}
            self.assertIn("process_started", stored_types)
            self.assertIn("process_exited", stored_types)
            service.close()


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