"""Operator CLI for Petri identities, printable QR labels, and history export."""

from __future__ import annotations

import argparse
from pathlib import Path
from typing import Optional, Sequence

try:
    from .petri_workflow import PetriRegistry, render_qr_label
except ImportError:
    from petri_workflow import PetriRegistry, render_qr_label


def _parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--database",
        type=Path,
        default=Path("/var/lib/labcobot/petri-workflow.sqlite3"),
    )
    commands = parser.add_subparsers(dest="command", required=True)

    create = commands.add_parser("create", help="register a plate")
    create.add_argument("--plate-id")
    create.add_argument("--label", default="")
    create.add_argument("--qr-label", type=Path)

    export = commands.add_parser("export-table", help="export QR table CSV")
    export.add_argument("--output", type=Path, required=True)

    import_table = commands.add_parser("import-table", help="import QR table CSV")
    import_table.add_argument("--input", type=Path, required=True)

    history = commands.add_parser("export-history", help="export observations CSV")
    target = history.add_mutually_exclusive_group(required=True)
    target.add_argument("--plate-id")
    target.add_argument("--cluster-id")
    history.add_argument("--output", type=Path, required=True)
    return parser


def _write_text(path: Path, text: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_name(".{}.tmp".format(path.name))
    temporary.write_text(text, encoding="utf-8")
    temporary.replace(path)


def main(argv: Optional[Sequence[str]] = None) -> int:
    args = _parser().parse_args(argv)
    registry = PetriRegistry(args.database)
    if args.command == "create":
        identity = registry.create_plate(args.plate_id, label=args.label)
        if args.qr_label:
            render_qr_label(identity, args.qr_label)
        print(identity.qr_payload)
        return 0
    if args.command == "export-table":
        _write_text(args.output, registry.export_plate_table())
        return 0
    if args.command == "import-table":
        count = registry.import_plate_table(
            args.input.read_text(encoding="utf-8")
        )
        print("Imported {} plate identities".format(count))
        return 0
    if args.command == "export-history":
        _write_text(
            args.output,
            registry.export_history_csv(
                plate_id=args.plate_id,
                cluster_id=args.cluster_id,
            ),
        )
        return 0
    raise RuntimeError("unsupported command")


if __name__ == "__main__":
    raise SystemExit(main())
