import sqlite3
from tempfile import TemporaryDirectory
from pathlib import Path


def consume(db, source, event, amount):
    with db:
        added = db.execute("insert into seen values(?,?,?) on conflict(source,event) do nothing", (source,event,amount)).rowcount
        if not added:
            old = db.execute("select amount from seen where source=? and event=?", (source,event)).fetchone()[0]
            return "重复跳过" if old == amount else "拒绝冲突"
        db.execute("insert into ledger values(?)", (amount,))
        return "首次处理"


with TemporaryDirectory() as tmp:
    db = sqlite3.connect(Path(tmp) / "sample.db")
    db.executescript("create table seen(source,event,amount,primary key(source,event));create table ledger(amount);")
    results = [consume(db, "sensor-A", event, value) for event,value in [("one",10),("one",10),("two",10),("one",11)]]
    count, total = db.execute("select count(*),sum(amount) from ledger").fetchone()
    db.close()
    assert results == ["首次处理","重复跳过","首次处理","拒绝冲突"] and (count,total)==(2,20)
    print("、".join(results), f"业务执行 {count} 次，总量 {total}")
