"""Teaching implementation: local logical deletion, not a privacy connector."""
from dataclasses import dataclass, field
import sqlite3


class DestinationUnavailable(Exception):
    pass


@dataclass
class Store:
    name: str
    connection: sqlite3.Connection
    fail_next_delete: bool = False

    def delete(self, subject):
        if self.fail_next_delete:
            self.fail_next_delete = False
            raise DestinationUnavailable(self.name)
        with self.connection:
            self.connection.execute("DELETE FROM records WHERE subject = ?", (subject,))

    def contains(self, subject):
        return self.connection.execute(
            "SELECT COUNT(*) FROM records WHERE subject = ?", (subject,)
        ).fetchone()[0] != 0


def buggy_delete(stores, subject):
    """Deliberate defect: a primary-store success hides a secondary failure."""
    stores[0].delete(subject)
    try:
        stores[1].delete(subject)
    except DestinationUnavailable:
        pass
    return "complete"


@dataclass
class Request:
    subject: str
    stores: list
    state: str = "unresolved"
    attempts: int = 0
    destinations: dict = field(default_factory=dict)

    def attempt(self):
        self.attempts += 1
        self.destinations = {}
        for store in self.stores:
            try:
                store.delete(self.subject)
                self.destinations[store.name] = (
                    "unresolved" if store.contains(self.subject) else "absent"
                )
            except DestinationUnavailable:
                self.destinations[store.name] = "unavailable"
        self.state = (
            "complete" if all(v == "absent" for v in self.destinations.values())
            and bool(self.stores) else "unresolved"
        )
        return self.snapshot()

    def reconcile(self):
        """Explicit caller-triggered observation, not automatic backup monitoring."""
        self.destinations = {
            store.name: "present" if store.contains(self.subject) else "absent"
            for store in self.stores
        }
        self.state = (
            "complete" if bool(self.stores)
            and all(v == "absent" for v in self.destinations.values()) else "unresolved"
        )
        return self.snapshot()

    def snapshot(self):
        return {"state": self.state, "attempts": self.attempts,
                "destinations": dict(self.destinations)}
