"""Test-owned observation and typed literal oracle, separate from the worker."""

import hashlib
import tempfile
import traceback
from pathlib import Path

from batch import (apply_batch_always_noop, apply_batch_baseline,
                   apply_batch_corrected, connect, initialize)

ROOT = Path(__file__).resolve().parent
IMPLEMENTATIONS = {"baseline": apply_batch_baseline, "corrected": apply_batch_corrected,
                   "always-noop": apply_batch_always_noop}


def same_typed_structure(actual, expected):
    if type(actual) is not type(expected):
        return False
    if type(expected) is dict:
        return actual.keys() == expected.keys() and all(
            same_typed_structure(actual[key], expected[key]) for key in expected)
    if type(expected) is list:
        return len(actual) == len(expected) and all(
            same_typed_structure(left, right) for left, right in zip(actual, expected))
    return actual == expected


def observe_rows(db):
    return [list(row) for row in db.execute(
        "SELECT record_id, body FROM stored_records ORDER BY record_id")]


def observe(implementation, batch):
    if type(batch) is not list or not all(type(body) is str for body in batch):
        raise ValueError("Fixture violates list[str] direct-call precondition")
    with tempfile.TemporaryDirectory(prefix="empty-batch-case-") as directory:
        path = Path(directory) / "case.sqlite3"
        db = connect(path)
        initialize(db)
        before = observe_rows(db)
        settings = {"isolation_level": db.isolation_level,
                    "autocommit_attribute": getattr(db, "autocommit", "unavailable"),
                    "journal_mode": db.execute("PRAGMA journal_mode").fetchone()[0],
                    "synchronous": db.execute("PRAGMA synchronous").fetchone()[0],
                    "in_transaction_before": db.in_transaction}
        response, error = None, None
        try:
            response = IMPLEMENTATIONS[implementation](db, batch)
        except Exception as caught:
            last = traceback.extract_tb(caught.__traceback__)[-1]
            error = {"type": type(caught).__name__, "message": str(caught),
                     "site": {"file": Path(last.filename).name, "function": last.name,
                              "line": last.lineno, "source_line": last.line},
                     "implementation_source_sha256": hashlib.sha256((ROOT / "batch.py").read_bytes()).hexdigest()}
        immediate = observe_rows(db)
        in_transaction_after = db.in_transaction
        db.close()
        db = connect(path)
        reopened = observe_rows(db)
        db.close()
    return {"implementation": implementation, "batch": batch,
            "before_rows": before, "response": response, "caught_exception": error,
            "immediate_after_rows": immediate, "rows_after_reconnect": reopened,
            "in_transaction_after": in_transaction_after, "connection_settings": settings,
            "observation_kind": "Harness catches an exception from the real callable, if raised; this is not an uncaught child-process termination."}


def signature(observation):
    error = observation["caught_exception"]
    if error is None:
        return None
    return {"type": error["type"], "message": error["message"],
            "site": error["site"], "implementation_source_sha256": error["implementation_source_sha256"]}
