import os
import tempfile
import unittest
from pathlib import Path

from cleanup.engine import CleanupEngine, SafetyRating
from core.transaction import TransactionStore
from recovery.manager import RecoveryManager
from remediation.quarantine import QuarantineVault


class TestRemediationFoundation(unittest.TestCase):
    def test_transaction_store_persists_status_and_actions(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            store = TransactionStore(Path(tmpdir) / "transactions.db")
            tx = store.create_transaction(
                finding_id="F-001",
                requested_action="quarantine_temp_file",
                before_state={"path": "C:/Temp/test.tmp"},
            )
            store.append_backup(tx["transaction_id"], {"path": "C:/Temp/test.tmp", "kind": "file"})
            store.record_action(tx["transaction_id"], "copy", "quarantine")
            store.update_status(tx["transaction_id"], "BACKED_UP")
            persisted = store.get_transaction(tx["transaction_id"])

            self.assertEqual(persisted["status"], "BACKED_UP")
            self.assertIn("copy", persisted["actions_attempted"])
            self.assertEqual(persisted["backup_objects"][0]["kind"], "file")

    def test_quarantine_vault_copies_file_and_restores_without_overwrite(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            root = Path(tmpdir)
            source = root / "bad.exe"
            source.write_bytes(b"not-a-real-malware")

            vault = QuarantineVault(root / "quarantine")
            meta = vault.quarantine_file(
                str(source),
                finding_id="F-002",
                transaction_id="TX-002",
                reason="High-confidence suspicious executable",
            )

            self.assertTrue(Path(meta["quarantine_path"]).exists())
            self.assertTrue(vault.verify_quarantine(meta["quarantine_id"]))

            restored_target = root / "restored.exe"
            restored_path = vault.restore_file(meta["quarantine_id"], str(restored_target))
            self.assertTrue(Path(restored_path).exists())
            self.assertEqual(Path(restored_path).read_bytes(), b"not-a-real-malware")

    def test_recovery_snapshot_records_manifest(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            root = Path(tmpdir)
            affected = root / "example.txt"
            affected.write_text("hello recovery", encoding="utf-8")

            manager = RecoveryManager(root / "recovery")
            snapshot = manager.capture_snapshot(
                transaction_id="TX-003",
                affected_paths=[str(affected)],
                metadata={"finding": "demo", "risk_score": 80},
            )

            self.assertTrue(Path(snapshot["snapshot_dir"]).exists())
            manifest_path = Path(snapshot["snapshot_dir"]) / "manifest.json"
            self.assertTrue(manifest_path.exists())
            self.assertEqual(snapshot["affected_files"][0]["path"], str(affected))

    def test_cleanup_engine_identifies_green_files(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            base = Path(tmpdir)
            temp_dir = base / "junk"
            temp_dir.mkdir()
            junk_file = temp_dir / "note.tmp"
            junk_file.write_bytes(b"temporary junk")

            engine = CleanupEngine(base_paths=[str(temp_dir)])
            candidates = engine.scan_candidates()

            self.assertTrue(any(candidate.category == "temporary_file" for candidate in candidates))
            self.assertTrue(any(candidate.safety_rating == SafetyRating.GREEN for candidate in candidates))


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