#!/usr/bin/env python3
"""Local form-acceptance demo: Python 3.9+, SQLite 3.24+, no dependencies.

Runs synthetic checks in memory. No network, file writes, CRM or ad-platform calls.
This is a storage boundary, not a public HTTP endpoint or a bot detector.
The caller must supply normalized, server-validated data and trusted decisions.
"""

import hashlib
import json
import sqlite3
import uuid


def open_demo_database():
    db = sqlite3.connect(":memory:", isolation_level=None)
    db.execute("PRAGMA foreign_keys = ON")
    db.executescript("""
        CREATE TABLE leads (
            id TEXT PRIMARY KEY,
            trusted_scope TEXT NOT NULL,
            submission_key TEXT NOT NULL,
            payload_hash TEXT NOT NULL,
            payload_json TEXT NOT NULL,
            state TEXT NOT NULL DEFAULT 'received',
            UNIQUE (trusted_scope, submission_key)
        );
        CREATE TABLE conversion_outbox (
            lead_id TEXT NOT NULL REFERENCES leads(id),
            event_name TEXT NOT NULL,
            state TEXT NOT NULL DEFAULT 'pending',
            UNIQUE (lead_id, event_name)
        );
    """)
    return db


# BEGIN STORAGE EXAMPLE
def store_accepted_lead(db, trusted_scope, submission_key, normalized_payload,
                        *, server_validated, server_challenge_passed):
    # These decisions come from your server, never request-body flags.
    if server_validated is not True or server_challenge_passed is not True:
        return {"accepted": False, "reason": "validation_or_challenge_failed"}
    # Scope is bound to a trusted form/session. A key identifies ONE attempt.
    if any(not isinstance(value, str) or not 1 <= len(value) <= 200
           for value in (trusted_scope, submission_key)):
        return {"accepted": False, "reason": "invalid_scope_or_key"}
    payload = json.dumps(normalized_payload, sort_keys=True,
                         separators=(",", ":"), ensure_ascii=False, allow_nan=False)
    digest = hashlib.sha256(payload.encode("utf-8")).hexdigest()
    db.execute("BEGIN IMMEDIATE")
    try:
        db.execute("""
            INSERT INTO leads
                (id, trusted_scope, submission_key, payload_hash, payload_json)
            VALUES (?, ?, ?, ?, ?)
            ON CONFLICT (trusted_scope, submission_key) DO NOTHING
        """, (str(uuid.uuid4()), trusted_scope, submission_key, digest, payload))
        lead_id, previous_digest = db.execute("""
            SELECT id, payload_hash FROM leads
            WHERE trusted_scope = ? AND submission_key = ?
        """, (trusted_scope, submission_key)).fetchone()
        if previous_digest != digest:
            db.execute("ROLLBACK")
            return {"accepted": False, "reason": "key_payload_conflict"}
        # A pending local job is not a delivered or attributed conversion.
        db.execute("""
            INSERT INTO conversion_outbox (lead_id, event_name)
            VALUES (?, 'lead_received')
            ON CONFLICT (lead_id, event_name) DO NOTHING
        """, (lead_id,))
        db.execute("COMMIT")
    except Exception:
        if db.in_transaction:
            db.execute("ROLLBACK")
        raise  # No accepted response on a storage/queue failure.
    return {"accepted": True, "leadId": lead_id, "stage": "received"}
# END STORAGE EXAMPLE


def run_checks():
    db = open_demo_database()
    payload = {"email": "synthetic@example.invalid", "service": "demo"}
    passed = []

    def check(condition, label):
        if not condition:
            raise AssertionError(label)
        passed.append(label)

    def counts(connection=db):
        return tuple(connection.execute("SELECT COUNT(*) FROM " + table).fetchone()[0]
                     for table in ("leads", "conversion_outbox"))

    def submit(key, data=payload, scope="trusted-demo-session", valid=True, challenge=True):
        return store_accepted_lead(db, scope, key, data,
                                   server_validated=valid, server_challenge_passed=challenge)

    result = submit("invalid", valid=False)
    check(result["accepted"] is False and counts() == (0, 0), "invalid form rejected")
    result = submit("challenge-failed", challenge=False)
    check(result["accepted"] is False and counts() == (0, 0), "failed challenge rejected")
    result = submit("truthy-flags", valid="true", challenge="true")
    check(result["accepted"] is False and counts() == (0, 0), "truthy flags rejected")

    accepted = submit("same-attempt")
    # Simulate the response being lost; the client retries the same payload/key.
    retry = submit("same-attempt", dict(reversed(list(payload.items()))))
    check(accepted["accepted"] is True and accepted == retry and counts() == (1, 1),
          "lost-response retry returns one durable lead and job")
    conflict = submit("same-attempt", {**payload, "service": "changed"})
    check(conflict["reason"] == "key_payload_conflict" and counts() == (1, 1),
          "changed payload conflicts without adding a lead or job")
    other_scope = submit("same-attempt", scope="another-trusted-session")
    check(other_scope["accepted"] is True and other_scope["leadId"] != accepted["leadId"]
          and counts() == (2, 2), "key is scoped to the trusted session")
    fresh = submit("new-intentional-enquiry")
    check(fresh["accepted"] is True and fresh["leadId"] != accepted["leadId"]
          and counts() == (3, 3), "new intentional enquiry gets a new key")

    broken = open_demo_database()
    broken.execute("""
        CREATE TRIGGER fail_queue BEFORE INSERT ON conversion_outbox
        BEGIN SELECT RAISE(ABORT, 'synthetic queue failure'); END;
    """)
    failed = False
    try:
        store_accepted_lead(broken, "trusted-demo-session", "storage-failure", payload,
                            server_validated=True, server_challenge_passed=True)
    except sqlite3.IntegrityError:
        failed = True
    check(failed and counts(broken) == (0, 0) and not broken.in_transaction,
          "queue failure rolls back the lead and never returns accepted")
    db.close()
    broken.close()
    print(json.dumps({"checks_passed": len(passed), "checks": passed}, indent=2))


if __name__ == "__main__":
    run_checks()
