"""Original fictional batch worker. No HTTP/parser, queue, retry or network API.

Direct-call precondition: type(batch) is list and every item is exact str.
Blankness classification uses strip(); usable text is stored unchanged.
"""

import sqlite3


def connect(path):
    options = {"isolation_level": None}
    if hasattr(sqlite3, "LEGACY_TRANSACTION_CONTROL"):
        options["autocommit"] = sqlite3.LEGACY_TRANSACTION_CONTROL
    db = sqlite3.connect(str(path), **options)
    db.execute("PRAGMA journal_mode = DELETE")
    db.execute("PRAGMA synchronous = FULL")
    return db


def initialize(db):
    db.executescript("""
        CREATE TABLE stored_records (
            record_id INTEGER PRIMARY KEY,
            body TEXT NOT NULL
        );
        INSERT INTO stored_records VALUES (1, 'preexisting');
    """)


def _persist_usable(db, usable):
    # This first access supplies the first actual INSERT, not a crash-only probe.
    first = usable[0]
    db.execute("BEGIN IMMEDIATE")
    try:
        db.execute("INSERT INTO stored_records (body) VALUES (?)", (first,))
        db.executemany("INSERT INTO stored_records (body) VALUES (?)",
                       [(body,) for body in usable[1:]])
        db.execute("COMMIT")
    except sqlite3.Error:
        if db.in_transaction:
            db.execute("ROLLBACK")
        raise
    return first


def apply_batch_baseline(db, batch):
    usable = [body for body in batch if body.strip()]
    first = _persist_usable(db, usable)
    return {"status": "applied", "first": first, "stored": len(usable),
            "skipped": len(batch) - len(usable)}


def apply_batch_corrected(db, batch):
    if not batch:
        return {"status": "noop", "first": None, "stored": 0, "skipped": 0}
    usable = [body for body in batch if body.strip()]
    if not usable:
        return {"status": "rejected", "reason": "no_usable_records",
                "stored": 0, "skipped": len(batch)}
    first = _persist_usable(db, usable)
    return {"status": "applied", "first": first, "stored": len(usable),
            "skipped": len(batch) - len(usable)}


def apply_batch_always_noop(db, batch):
    """Deliberately wrong patch: stops exceptions while dropping usable work."""
    return {"status": "noop", "first": None, "stored": 0, "skipped": 0}
