#!/usr/bin/env python3
"""Build or validate the immutable LAB E2 CVAT annotation handoff."""

from __future__ import annotations

import argparse
import hashlib
import json
from pathlib import Path

import k1link.compute.annotation_workspace as workspace_module
from k1link.compute import prepare_annotation_workspace, validate_annotation_workspace


def _sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def _arguments() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    commands = parser.add_subparsers(dest="command", required=True)
    prepare = commands.add_parser("prepare")
    prepare.add_argument("--evaluation-pack", type=Path, required=True)
    prepare.add_argument("--prelabels", type=Path, required=True)
    prepare.add_argument("--valid-fov-root", type=Path, required=True)
    prepare.add_argument("--output-root", type=Path, required=True)

    validate = commands.add_parser("validate")
    validate.add_argument("--workspace", type=Path, required=True)
    validate.add_argument("--evaluation-pack", type=Path, required=True)
    validate.add_argument("--prelabels", type=Path, required=True)
    validate.add_argument("--valid-fov-root", type=Path, required=True)
    return parser.parse_args()


def main() -> int:
    args = _arguments()
    if args.command == "prepare":
        result = prepare_annotation_workspace(
            evaluation_pack_root=args.evaluation_pack,
            prelabels_root=args.prelabels,
            valid_fov_root=args.valid_fov_root,
            output_root=args.output_root,
            producer_files=(
                (
                    "annotation_workspace.py",
                    _sha256(Path(str(workspace_module.__file__)).resolve(strict=True)),
                ),
                (
                    "prepare_e2_annotation_workspace.py",
                    _sha256(Path(__file__).resolve(strict=True)),
                ),
            ),
        )
    else:
        result = validate_annotation_workspace(
            args.workspace,
            evaluation_pack_root=args.evaluation_pack,
            prelabels_root=args.prelabels,
            valid_fov_root=args.valid_fov_root,
        )
    print(
        json.dumps(
            {
                "generation_id": result.generation_id,
                "root": str(result.root),
                "frame_count": result.frame_count,
                "draft_instance_count": result.draft_instance_count,
                "ground_truth": False,
            },
            sort_keys=True,
        )
    )
    return 0


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