#!/usr/bin/env python3
"""Offline rule demonstrations. No LLM, CRM, calendar API or network. Python 3."""
import concurrent.futures
import json
import sqlite3
import tempfile
from datetime import date
from pathlib import Path


def run():
    # Sales: same operation twice, not two independent customer inquiries.
    event = {'operation': 'op-sales-1', 'service': 'kitchen', 'dimensions': '3x2', 'month': 'December'}
    naive_sales = [dict(event), dict(event)]
    ledger = {}
    def save(item):
        key = item['operation']
        if key not in ledger:
            ledger[key] = {'id': 'lead-demo-1', **item}
        return ledger[key]['id']
    first, repeat = save(event), save(event)
    assert len(naive_sales) == 2 and len(ledger) == 1 and first == repeat
    # Support: a found text is not automatically a current approved answer.
    card = {'id': 'KB-RETURN-1', 'status': 'approved', 'review_at': '2026-10-01', 'answer': 'demo-only rule'}
    def answer(item, today):
        return 'answer' if item and item['status'] == 'approved' and today <= date.fromisoformat(item['review_at']) else 'handoff'
    stale = answer(card, date(2026, 10, 27))
    current = answer({**card, 'review_at': '2026-11-01'}, date(2026, 10, 27))
    assert stale == 'handoff' and current == 'answer' and answer(None, date(2026, 10, 27)) == 'handoff'
    # Booking: two reads may both report free; uniqueness must hold at the write.
    with tempfile.TemporaryDirectory(prefix='booking-demo-') as folder:
        dbpath = Path(folder) / 'slots.sqlite'
        with sqlite3.connect(dbpath) as db:
            db.execute('CREATE TABLE bookings (operation TEXT PRIMARY KEY, slot TEXT UNIQUE NOT NULL)')
        def book(operation):
            with sqlite3.connect(dbpath, timeout=5) as db:
                db.execute('BEGIN IMMEDIATE')
                existing = db.execute('SELECT rowid FROM bookings WHERE operation=?', (operation,)).fetchone()
                if existing:
                    return {'status': 'accepted', 'id': existing[0], 'operation': operation}
                try:
                    row = db.execute('INSERT INTO bookings VALUES (?,?)', (operation, '2026-11-01T15:00+03:00'))
                    return {'status': 'accepted', 'id': row.lastrowid, 'operation': operation}
                except sqlite3.IntegrityError:
                    return {'status': 'conflict', 'operation': operation}
        # Both naive readers see an empty schedule before either write.
        with sqlite3.connect(dbpath) as db:
            reads = [db.execute('SELECT count(*) FROM bookings').fetchone()[0] == 0 for _ in range(2)]
        with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
            outcomes = list(pool.map(book, ['op-booking-1', 'op-booking-2']))
        winner = next(x for x in outcomes if x['status'] == 'accepted')
        retry = book(winner['operation'])
        with sqlite3.connect(dbpath) as db:
            count = db.execute('SELECT count(*) FROM bookings').fetchone()[0]
        assert all(reads) and sorted(x['status'] for x in outcomes) == ['accepted', 'conflict']
        assert retry['id'] == winner['id'] and count == 1
    return {'passed': True, 'sales': {'beforeRows': 2, 'afterRows': 1, 'sameIdOnRetry': True},
            'support': {'before': 'answer', 'staleAfter': stale, 'validAfter': current, 'missingAfter': 'handoff'},
            'booking': {'naiveFreeReads': 2, 'after': ['accepted', 'conflict'], 'rows': count, 'sameIdOnRetry': True},
            'limits': ['No LLM or retrieval quality test', 'No real CRM/helpdesk/calendar',
                       'Equal slots only; no overlapping durations, resources or timezone migration'],
            'networkRequests': 0, 'clientResultsClaimed': False}


if __name__ == '__main__':
    print(json.dumps(run(), ensure_ascii=False, indent=2))
