"""OMEGANEON reproducible local workflow failure-injection demo.

Run: python -m unittest -v workflow_failure_injection_tests.py
Python: 3.9+; standard library only.

This is a deterministic local simulation. It uses a stand-in decision agent and
SQLite-backed stand-in external CRM, not a real LLM or SaaS integration.
The reviewer_role string and tenant comparison are simplified test doubles,
not real authentication, authorization, or a complete APB implementation.
"""
from __future__ import annotations

import hashlib
import json
import sqlite3
import tempfile
import unittest
from pathlib import Path


class WorkerCrash(RuntimeError):
    pass


class ExternalTimeout(RuntimeError):
    pass


class WorkflowEngine:
    """Durable state + fixed approval boundary + idempotent side-effect stub."""

    def __init__(self, db_path: Path):
        self.db_path = db_path
        with self.db() as conn:
            conn.executescript("""
                CREATE TABLE IF NOT EXISTS workflow (
                    id TEXT PRIMARY KEY,
                    tenant TEXT NOT NULL,
                    target_tenant TEXT NOT NULL,
                    status TEXT NOT NULL,
                    proposal TEXT NOT NULL,
                    approved_fingerprint TEXT
                );
                CREATE TABLE IF NOT EXISTS crm_actions (
                    idempotency_key TEXT PRIMARY KEY,
                    tenant TEXT NOT NULL,
                    payload TEXT NOT NULL
                );
                CREATE TABLE IF NOT EXISTS audit (
                    sequence INTEGER PRIMARY KEY AUTOINCREMENT,
                    workflow_id TEXT NOT NULL,
                    event TEXT NOT NULL
                );
            """)

    def db(self):
        connection = sqlite3.connect(str(self.db_path))
        connection.row_factory = sqlite3.Row
        return connection

    def _audit(self, conn, workflow_id: str, event: str):
        conn.execute("INSERT INTO audit (workflow_id, event) VALUES (?, ?)", (workflow_id, event))

    @staticmethod
    def _fingerprint(tenant: str, target_tenant: str, proposal: str) -> str:
        document = json.dumps({
            "tenant": tenant,
            "target_tenant": target_tenant,
            "action": "create_cs_handoff",
            "proposal": proposal,
        }, sort_keys=True)
        return hashlib.sha256(document.encode("utf-8")).hexdigest()

    def start(self, workflow_id: str, tenant: str, target_tenant: str, deal_note: str):
        # This placeholder models a potentially non-deterministic agent's output.
        # The output is DATA; it never authorizes a tool call.
        proposal = f"CS handoff draft: {deal_note}"
        with self.db() as conn:
            inserted = conn.execute(
                """INSERT OR IGNORE INTO workflow
                (id, tenant, target_tenant, status, proposal)
                VALUES (?, ?, ?, 'AWAITING_APPROVAL', ?)""",
                (workflow_id, tenant, target_tenant, proposal),
            ).rowcount
            if inserted:
                self._audit(conn, workflow_id, "proposal_created")

    def status(self, workflow_id: str) -> str:
        with self.db() as conn:
            row = conn.execute("SELECT status FROM workflow WHERE id=?", (workflow_id,)).fetchone()
        if row is None:
            raise KeyError(workflow_id)
        return row["status"]

    def approve(self, workflow_id: str, reviewer_role: str):
        with self.db() as conn:
            row = conn.execute("SELECT * FROM workflow WHERE id=?", (workflow_id,)).fetchone()
            if not row:
                raise KeyError(workflow_id)
            if reviewer_role != "authorized_reviewer":
                self._audit(conn, workflow_id, "approval_denied_unauthorized_reviewer")
                raise PermissionError("Reviewer is not authorized")
            if row["status"] != "AWAITING_APPROVAL":
                raise ValueError("Workflow is not awaiting approval")
            fingerprint = self._fingerprint(row["tenant"], row["target_tenant"], row["proposal"])
            conn.execute("UPDATE workflow SET status='APPROVED', approved_fingerprint=? WHERE id=?",
                         (fingerprint, workflow_id))
            self._audit(conn, workflow_id, "approved")

    def reject(self, workflow_id: str, reviewer_role: str):
        if reviewer_role != "authorized_reviewer":
            raise PermissionError("Reviewer is not authorized")
        with self.db() as conn:
            result = conn.execute(
                "UPDATE workflow SET status='REJECTED' WHERE id=? AND status='AWAITING_APPROVAL'",
                (workflow_id,),
            )
            if result.rowcount != 1:
                raise ValueError("Workflow is not awaiting approval")
            self._audit(conn, workflow_id, "rejected")

    def execute(self, workflow_id: str, *, timeout_before_send: bool = False,
                crash_after_send: bool = False):
        with self.db() as conn:
            row = conn.execute("SELECT * FROM workflow WHERE id=?", (workflow_id,)).fetchone()
            if not row:
                raise KeyError(workflow_id)
            if row["status"] == "COMPLETED":
                return
            if row["status"] != "APPROVED":
                raise PermissionError("Execution requires an approved workflow")
            # APB enforced in code, not by model instructions.
            expected = self._fingerprint(row["tenant"], row["target_tenant"], row["proposal"])
            if row["tenant"] != row["target_tenant"] or row["approved_fingerprint"] != expected:
                conn.execute("UPDATE workflow SET status='BLOCKED' WHERE id=?", (workflow_id,))
                self._audit(conn, workflow_id, "policy_blocked")
                return
        # Transient error occurs BEFORE any external side effect.
        if timeout_before_send:
            with self.db() as conn:
                self._audit(conn, workflow_id, "external_timeout")
            raise ExternalTimeout("Simulated temporary CRM outage")

        # Separate commit models a remote system that accepts an idempotency key.
        # If the worker crashes immediately after the write, the workflow state
        # remains APPROVED and retrying reuses the same idempotency key.
        idempotency_key = f"{workflow_id}:create_cs_handoff"
        with self.db() as external_conn:
            external_conn.execute(
                "INSERT OR IGNORE INTO crm_actions (idempotency_key, tenant, payload) VALUES (?, ?, ?)",
                (idempotency_key, row["tenant"], row["proposal"]),
            )
        if crash_after_send:
            raise WorkerCrash("Simulated crash after CRM accepted the action")
        with self.db() as conn:
            conn.execute("UPDATE workflow SET status='COMPLETED' WHERE id=?", (workflow_id,))
            self._audit(conn, workflow_id, "completed")

    def action_count(self, workflow_id: str) -> int:
        with self.db() as conn:
            row = conn.execute("SELECT COUNT(*) AS n FROM crm_actions WHERE idempotency_key=?",
                               (f"{workflow_id}:create_cs_handoff",)).fetchone()
            return row["n"]

    def audit_events(self, workflow_id: str):
        with self.db() as conn:
            return [r["event"] for r in conn.execute(
                "SELECT event FROM audit WHERE workflow_id=? ORDER BY sequence", (workflow_id,))]


class ProductionBoundaryTests(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.TemporaryDirectory()
        self.engine = WorkflowEngine(Path(self.tmp.name) / "workflow.db")

    def tearDown(self):
        self.tmp.cleanup()

    def test_01_happy_path(self):
        self.engine.start("deal-1", "tenant-A", "tenant-A", "Acme renewal plan")
        self.assertEqual(self.engine.status("deal-1"), "AWAITING_APPROVAL")
        self.engine.approve("deal-1", "authorized_reviewer")
        self.engine.execute("deal-1")
        self.assertEqual(self.engine.status("deal-1"), "COMPLETED")
        self.assertEqual(self.engine.action_count("deal-1"), 1)

    def test_02_crash_and_recovery_no_duplicate_action(self):
        self.engine.start("deal-2", "tenant-A", "tenant-A", "Support requirements")
        self.engine.approve("deal-2", "authorized_reviewer")
        with self.assertRaises(WorkerCrash):
            self.engine.execute("deal-2", crash_after_send=True)
        self.assertEqual(self.engine.status("deal-2"), "APPROVED")
        # Simulate a fresh worker process reconstructing from persisted state.
        self.engine = WorkflowEngine(self.engine.db_path)
        self.engine.execute("deal-2")
        self.assertEqual(self.engine.status("deal-2"), "COMPLETED")
        self.assertEqual(self.engine.action_count("deal-2"), 1)

    def test_03_duplicate_event_does_not_create_extra_work(self):
        self.engine.start("deal-3", "tenant-A", "tenant-A", "Original")
        self.engine.start("deal-3", "tenant-A", "tenant-A", "Duplicate webhook")
        self.engine.approve("deal-3", "authorized_reviewer")
        self.engine.execute("deal-3")
        self.engine.execute("deal-3")
        self.assertEqual(self.engine.action_count("deal-3"), 1)
        self.assertEqual(self.engine.audit_events("deal-3").count("proposal_created"), 1)

    def test_04_tenant_boundary_blocks_cross_tenant_write(self):
        self.engine.start("deal-4", "tenant-A", "tenant-B", "Wrong target")
        self.engine.approve("deal-4", "authorized_reviewer")
        self.engine.execute("deal-4")
        self.assertEqual(self.engine.status("deal-4"), "BLOCKED")
        self.assertEqual(self.engine.action_count("deal-4"), 0)

    def test_05_rejection_and_unauthorized_approval(self):
        self.engine.start("deal-5", "tenant-A", "tenant-A", "Sensitive request")
        with self.assertRaises(PermissionError):
            self.engine.approve("deal-5", "untrusted_user")
        self.engine.reject("deal-5", "authorized_reviewer")
        with self.assertRaises(PermissionError):
            self.engine.execute("deal-5")
        self.assertEqual(self.engine.action_count("deal-5"), 0)

    def test_06_transient_failure_preserves_workflow(self):
        self.engine.start("deal-6", "tenant-A", "tenant-A", "Customer needs")
        self.engine.approve("deal-6", "authorized_reviewer")
        with self.assertRaises(ExternalTimeout):
            self.engine.execute("deal-6", timeout_before_send=True)
        self.assertEqual(self.engine.status("deal-6"), "APPROVED")
        self.engine.execute("deal-6")
        self.assertEqual(self.engine.action_count("deal-6"), 1)

    def test_07_approval_bound_to_specific_payload(self):
        self.engine.start("deal-7", "tenant-A", "tenant-A", "Approved content")
        self.engine.approve("deal-7", "authorized_reviewer")
        with self.engine.db() as conn:
            conn.execute("UPDATE workflow SET proposal=? WHERE id=?", ("Changed after approval", "deal-7"))
        self.engine.execute("deal-7")
        self.assertEqual(self.engine.status("deal-7"), "BLOCKED")
        self.assertEqual(self.engine.action_count("deal-7"), 0)


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