"""Compare returned document identities using a pinned Machina source archive."""
import argparse
import asyncio
import hashlib
import json
from pathlib import Path
import sys
import zipfile


COMMIT = "d368d1f211c6a8115e2ea9265a7bd7d513a3be4f"
ARCHIVE_SHA = "e93affc9b95eba0be4edea7a75bb23b6ab65cd26c28c7ba38e5a207e3625fe21"
MANUAL = "pump_p201_manual.md"
MARKER = b"CLASSROOM-REVISION-B"
SECTION = b"#### 2.2 Quarterly Inspection"


def digest(data):
    return hashlib.sha256(data).hexdigest()


def read_source(path):
    if digest(path.read_bytes()) != ARCHIVE_SHA:
        raise ValueError("Source ZIP SHA-256 mismatch. Get the linked revision.")
    prefix = "machina-" + COMMIT + "/"
    with zipfile.ZipFile(path) as archive:
        original = archive.read(prefix + "examples/sample_data/manuals/" + MANUAL)
    sys.path.insert(0, str(path.resolve()) + "/" + prefix + "src")
    return original


def no_external_io(event, args):
    if event in {"socket.connect", "socket.bind", "socket.getaddrinfo", "socket.sendto",
                 "socket.sendmsg", "subprocess.Popen", "os.system", "os.posix_spawn"}:
        raise PermissionError("Offline exercise: " + event)


async def observe(label, source, output):
    from machina.connectors.docs.document_store import DocumentStoreConnector

    connector = DocumentStoreConnector(paths=[source])
    await connector.connect()
    try:
        health = await connector.health_check()
        if health.details.get("mode") != "keyword":
            raise ValueError("Use a fresh virtual environment with only the listed dependencies.")
        hits = await connector.search("nameplate", top_k=1)
        if len(hits) != 1:
            raise ValueError("Expected exactly one returned passage")
        hit = hits[0]
        passage = hit.content.encode("utf-8")
        text_file = output / (label + "-returned.txt")
        text_file.write_bytes(passage)
        snapshot_file = output / (label + "-input.md")
        snapshot_file.write_bytes(source.read_bytes())
        return dict(label=label, locator=str(source), file=source.name,
                    inputCopy=snapshot_file.name, inputSha256=digest(snapshot_file.read_bytes()),
                    section=hit.section_title, chunkId=hit.chunk_id, parentId=hit.parent_id,
                    returnedText=text_file.name, returnedSha256=digest(passage),
                    includesTeachingNote=MARKER in passage, mode=health.details["mode"])
    finally:
        await connector.disconnect()


async def exercise(archive, output):
    if output.exists():
        raise ValueError("Choose a new output directory. Existing records are preserved.")
    original = read_source(archive)
    if original.count(SECTION) != 1 or MARKER in original:
        raise ValueError("Cannot identify the alteration boundary")
    # Import before creating output. Missing dependencies must not leave a result.
    from machina.connectors.docs.document_store import DocumentStoreConnector  # noqa: F401

    output.mkdir()
    source = output / "same" / MANUAL
    source.parent.mkdir()
    source.write_bytes(original)
    rows = [await observe("original", source, output), await observe("repeat", source, output)]
    source.write_bytes(original.replace(SECTION, MARKER + b"\n\n" + SECTION))
    rows.append(await observe("edited", source, output))
    moved = output / "moved" / MANUAL
    moved.parent.mkdir()
    moved.write_bytes(original)
    rows.append(await observe("moved", moved, output))
    (output / "observations.json").write_text(json.dumps(rows, ensure_ascii=False, indent=2)+"\n", encoding="utf-8")
    for row in rows:
        print(row["label"], row["chunkId"], row["returnedSha256"], row["includesTeachingNote"])


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("archive", type=Path)
    parser.add_argument("output", type=Path)
    args = parser.parse_args()
    sys.addaudithook(no_external_io)
    try:
        asyncio.run(exercise(args.archive, args.output))
    except (OSError, ValueError, ImportError) as error:
        sys.exit(str(error))
