import os
import subprocess
import sys
import tempfile
import unittest

from core.audit import AuditLogger
from remediation.coordinator import RemediationCoordinator
from remediation.processes import ProcessRemediation


class TestSecurityRemediation(unittest.TestCase):
    def test_audit_logger_records_actions(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            audit = AuditLogger(os.path.join(tmpdir, "audit.db"))
            try:
                entry = audit.record("quarantine", "admin", "bad.exe", {"status": "moved"}, finding="F-01", transaction_id="TX-01")
                self.assertEqual(entry["action"], "quarantine")
                self.assertIn("F-01", audit.list_entries(10)[0]["details"])
            finally:
                audit.close()

    def test_remediation_coordinator_marks_success(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            coordinator = RemediationCoordinator(os.path.join(tmpdir, "tx.db"))
            try:
                tx = coordinator.execute("F-02", "quarantine_temp_file", {"backup_paths": ["C:/Temp/test.tmp"]})
                self.assertEqual(tx["status"], "SUCCESS")
            finally:
                coordinator.close()

    def test_process_remediation_handles_missing_process(self):
        result = ProcessRemediation().terminate(999999)
        self.assertEqual(result["status"], "missing")

    def test_process_remediation_verifies_stopped_state(self):
        proc = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"])
        try:
            result = ProcessRemediation().terminate(proc.pid)
            self.assertEqual(result["status"], "terminated")
            self.assertTrue(ProcessRemediation().verify_stopped(proc.pid))
        finally:
            if proc.poll() is None:
                proc.kill()
                proc.wait(timeout=5)


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