"""Create a real SQLite commit, then observe it through an application-owned reader.

Run with ``uv run --extra sqlite python examples/shared.py``. No source network
is contacted; the example explicitly trusts its temporary local database.
"""

import argparse
from datetime import UTC, datetime
from ipaddress import ip_network
from pathlib import Path
from tempfile import TemporaryDirectory

import anyio

from rpkiparrot.config import FreshnessPolicy, SharedReaderConfig
from rpkiparrot.models import ParsedDataset, PayloadKind, Vrp, VrpRecord
from rpkiparrot.persistence import SQLiteBackend, state_from_snapshot
from rpkiparrot.shared import SharedSnapshotClient
from rpkiparrot.store import MemoryStore
from rpkiparrot.validation import validate_origin


def write_fixture(path: Path) -> None:
    """The synchronous backend and store stay on this one managed worker."""
    store = MemoryStore()
    store.replace_source(
        "local-export",
        ParsedDataset(
            present=frozenset({PayloadKind.VRP}),
            generated_at=datetime.now(UTC),
            vrps=(VrpRecord(vrp=Vrp(prefix=ip_network("192.0.2.0/24"), max_length=24, asn=64496)),),
        ),
        freshness=FreshnessPolicy(max_age=300),
    )
    backend = SQLiteBackend(path)
    try:
        backend.open()
        backend.commit(state_from_snapshot(store.snapshot()), expected=None)
    finally:
        backend.close()


async def main(path: Path) -> None:
    await anyio.to_thread.run_sync(write_fixture, path)
    async with (
        SharedSnapshotClient(SharedReaderConfig(path=path)) as reader,
        anyio.create_task_group() as tasks,
    ):
        await tasks.start(reader.run)
        snapshot = await reader.wait_ready(required=frozenset({PayloadKind.VRP}))
        result = validate_origin(snapshot, "192.0.2.0/24", 64496)
        print(result.status.value)
        async with reader.watch() as subscription:
            assert subscription.initial_status is not None
            assert subscription.initial_status.snapshot_id == subscription.initial.id
            assert subscription.initial.id == snapshot.id
            assert subscription.initial.upstream_id is not None
            print("local reader and writer identities are separate")
        await reader.aclose()


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--backend", choices=("asyncio", "trio"), default="asyncio")
    options = parser.parse_args()
    with TemporaryDirectory() as directory:
        anyio.run(main, Path(directory) / "state.sqlite", backend=options.backend)
