"""SQLite + fake actuator crash experiment. NOT a Home Assistant integration."""
import json
import sqlite3
import tempfile
from pathlib import Path


class Tasks:
    def __init__(self, path):
        self.db = sqlite3.connect(path)
        self.db.execute('CREATE TABLE IF NOT EXISTS job (id INTEGER PRIMARY KEY, due INTEGER, state TEXT)')
        self.db.commit()

    def schedule(self, due):
        with self.db:
            self.db.execute("UPDATE job SET state='cancelled' WHERE state='pending'")
            cur = self.db.execute("INSERT INTO job(due,state) VALUES (?, 'pending')", (due,))
        return cur.lastrowid

    def due_job(self, now):
        return self.db.execute("SELECT id FROM job WHERE state='pending' AND due<=? ORDER BY id DESC LIMIT 1", (now,)).fetchone()

    def finish(self, job_id):
        with self.db:
            self.db.execute("UPDATE job SET state='done' WHERE id=? AND state='pending'", (job_id,))

    def close(self):
        self.db.close()


class Lamp:
    def __init__(self):
        self.on, self.calls = True, 0

    def act(self, action):
        self.calls += 1
        self.on = False if action == 'off' else not self.on


def attempt(tasks, lamp, now, boot, observation, crash=False, action='off'):
    # observation = (state, receive_time). Receipt must be post-boot and <=30 s old.
    job = tasks.due_job(now)
    state, received = observation
    if not job or state != 'off' or not (boot <= received <= now and now-received <= 30):
        return False
    lamp.act(action)
    if crash:
        return True  # simulate process loss before completion is committed
    tasks.finish(job[0])
    return True


def run():
    results = []
    with tempfile.TemporaryDirectory() as folder:
        # Different DB files isolate scenarios; reopening proves actual disk persistence.
        p = Path(folder)/'recovery.db'; t = Tasks(p); t.schedule(600); t.close()
        t = Tasks(p); lamp = Lamp()
        assert not attempt(t, lamp, 700, 690, ('off', 500))
        assert not attempt(t, lamp, 700, 690, ('unknown', 700))
        assert not attempt(t, lamp, 700, 690, ('on', 700))
        assert not attempt(t, lamp, 750, 690, ('off', 700))
        assert attempt(t, lamp, 750, 690, ('off', 750))
        assert not lamp.on and lamp.calls == 1
        assert not attempt(t, lamp, 751, 690, ('off', 751))
        t.close()
        results.append({'case': 'reopen_and_freshness_gates', 'calls': lamp.calls, 'lamp_on': lamp.on})
        for action in ['off', 'toggle']:
            p = Path(folder)/(action+'.db'); t = Tasks(p); t.schedule(600); lamp = Lamp()
            attempt(t, lamp, 700, 690, ('off', 700), crash=True, action=action)
            t.close(); t = Tasks(p)
            attempt(t, lamp, 710, 705, ('off', 710), action=action)
            assert lamp.calls == 2 and lamp.on == (action == 'toggle')
            t.close()
            results.append({'case': 'crash_after_action_'+action, 'calls': lamp.calls, 'lamp_on': lamp.on})
        p = Path(folder)/'replacement.db'; t = Tasks(p)
        old = t.schedule(600); new = t.schedule(900); t.finish(old)
        assert t.due_job(700) is None and t.due_job(901) == (new,)
        t.close()
        results.append({'case': 'old_completion_cannot_finish_new_task', 'old_id': old, 'new_id': new})
    return results


if __name__ == '__main__':
    print(json.dumps({'model': 'deadline-v1', 'passed': 4, 'cases': run()}, indent=2))
