"""The weights and test pages of examples/detector.pl, written from the music_deep detector.

    python detector.py [--checkpoint CKPT] [--out DIR] [PAGE ...]
    python detector.py --tiny [--out DIR]

run in the environment of ~/prog/music_deep (`mamba run -n pytorch`), writes in DIR (the
directory of this script by default):

    detector_weights.safetensors   the state_dict of the OMRDetector of CKPT, float32, as
                                   torch holds it, and in the metadata what the Prolog side
                                   needs and the state_dict does not say: the class names of
                                   each head, in the order of its logits, and the
                                   hyper-parameters of the model and of its preprocessing;
    detector_pages.safetensors     for each page K: pages.K, the image, uint8, grey [H, W]
                                   or of three channels [H, W, 3], and what torch computes for it, in float32 with no
                                   autocast: kept.K, the indices of the patches the variance
                                   drop keeps, sym_logits.K [Q, 83], sym_boxes.K [Q, 4],
                                   line_logits.K [Q, 8], line_keypoints.K [Q, 4], Q the
                                   kept patches times the 5 shapes, boxes and keypoints
                                   x1, y1, x2, y2 in patch units, as the model returns them.

A PAGE is the path of an image, grey or RGB, or PATH@Y,X,H,W for the crop of H rows and W
columns at Y, X; a grey one followed by +R,G,B is made an RGB page, its ink of that colour on
white: each channel g + (255 - g) * colour / 255. By default: a 1000 x 1000 crop of a Trompa
page, the whole of another one, and the crop again, its ink tinted, the RGB page.

With --tiny, no checkpoint and no data: a detector of the same structure and random weights,
seeded, patches of 8 x 8, 2 layers of 2 heads of 8, 4 symbol classes, 3 line classes and 2
shapes, and two random pages of 20 x 27 pixels, one grey and one RGB, some of their patches
flat, which the variance drops. Written as detector_tiny_weights.safetensors and
detector_tiny_pages.safetensors in DIR, ../test by default: the fixture of test/detector.plt,
small enough to be committed, where the files above are not.

The model is the one music_deep trains, with the attention of scaled_dot_product_attention,
as training runs it: its scale is 1/sqrt(128), the width of the rotated queries, where the
other path of vit.Attention takes dim_head**-0.5, 1/8. The safetensors files are written by
hand, the format being a JSON header and the bytes, so that the script needs no package
music_deep does not.

The files of the full model are not in the repository: the examples download them from the GitHub release
examples-data-1 where they are not beside the examples, see example_data.pl. A file written
again differs from its asset: upload it to a new release, and change release/1 and sha256/2
there.
"""

import argparse
import json
import struct
import sys
from pathlib import Path

import numpy as np
import torch
from PIL import Image

MUSIC_DEEP = Path.home() / "prog" / "music_deep"
sys.path.insert(0, str(MUSIC_DEEP / "src"))

from model.detector import OMRDetector, create_detector  # noqa: E402
from model.vit import ViT  # noqa: E402
from dataset.coco import parse_coco  # noqa: E402
import transform.core as core_tf  # noqa: E402

CHECKPOINT = (
    MUSIC_DEEP
    / "experiments/029_size_difficulty_balanced_loss/train_detection/checkpoints/latest_model.pt"
)
ANNOTATIONS = MUSIC_DEEP / "data/trompa-coco/annotations/instances_trainval2017.json"
IMAGES = MUSIC_DEEP / "data/trompa-coco/trainval2017"
PAGES = [
    f"{IMAGES}/Beethoven_Op119_Nr01-Breitkopf_001.tiff@3300,100,1000,1000",
    f"{IMAGES}/Beethoven_Op33_Nr3-Breitkopf_003.tiff",
    f"{IMAGES}/Beethoven_Op119_Nr01-Breitkopf_001.tiff@3300,100,1000,1000+200,40,0",
]
PATCH_SIZE = 64
VAR_THRESHOLD = 0.001
NUM_SHAPES = 5
BASE_ANCHOR_SIZE = 1.0
DTYPES = {np.dtype("float32"): "F32", np.dtype("int32"): "I32", np.dtype("uint8"): "U8"}


def save_safetensors(path, tensors, metadata):
    header = {}
    offset = 0
    for key, array in tensors.items():
        size = array.nbytes
        header[key] = {
            "dtype": DTYPES[array.dtype],
            "shape": list(array.shape),
            "data_offsets": [offset, offset + size],
        }
        offset += size
    if metadata:
        header["__metadata__"] = metadata
    text = json.dumps(header, separators=(",", ":")).encode()
    text += b" " * (-len(text) % 8)
    with open(path, "wb") as f:
        f.write(struct.pack("<Q", len(text)))
        f.write(text)
        for array in tensors.values():
            f.write(np.ascontiguousarray(array).tobytes())


def load_page(spec):
    spec, _, tint = spec.partition("+")
    path, _, crop = spec.partition("@")
    image = np.array(Image.open(path))
    if image.ndim == 3:
        image = image[:, :, :3]
    if crop:
        y, x, h, w = map(int, crop.split(","))
        image = image[y : y + h, x : x + w]
    if tint:
        if image.ndim != 2:
            raise ValueError(f"{path}: a tint is of a grey image, not of shape {image.shape}")
        colour = np.array([int(c) for c in tint.split(",")], dtype=np.float32)
        grey = image[:, :, None].astype(np.float32)
        image = np.rint(grey + (255 - grey) * colour / 255).astype(np.uint8)
    return np.ascontiguousarray(image)


@torch.no_grad()
def reference(model, image, device, patch_size=PATCH_SIZE):
    """What music_deep's inference computes for a uint8 image, grey [H, W] or [H, W, 3],
    before its top-k."""
    t = torch.from_numpy(image).to(device)
    t = t.unsqueeze(0).expand(3, -1, -1) if t.ndim == 2 else t.permute(2, 0, 1)
    t = core_tf.to_float1_img(core_tf.TensorImage(t))
    t = core_tf.pad_to_patch_size_img(t, (patch_size, patch_size))
    batched = core_tf.TensorImage(t.data.unsqueeze(0))
    patches = core_tf.extract_patches_img(batched, (patch_size, patch_size))
    kept = core_tf.variance_patch_drop_indices(patches.data, var_threshold=VAR_THRESHOLD)
    patches = core_tf.patch_drop_img(patches, kept)
    out = model(patches)
    f32 = lambda x: x.data[0].float().cpu().numpy()  # noqa: E731
    return {
        "kept": kept[0].to(torch.int32).cpu().numpy(),
        "sym_logits": f32(out.symbols.pred_logits),
        "sym_boxes": f32(out.symbols.pred_boxes),
        "line_logits": f32(out.lines.pred_logits),
        "line_keypoints": f32(out.lines.pred_keypoints),
    }


def export(model, device, config, images, weights_file, pages_file):
    """The weights of the model with config as metadata, and the pages, a dict of name to
    image, with what the model computes for each."""
    weights = {k: v.detach().float().contiguous().cpu().numpy() for k, v in model.state_dict().items()}
    metadata = {
        **config,
        "channels": "3",
        "heads": str(model.backbone.transformer.layers[0][0].heads),
        "dim_head": str(model.backbone.dim_head),
        "var_threshold": str(VAR_THRESHOLD),
    }
    save_safetensors(weights_file, weights, metadata)

    patch_size = int(config["patch_size"])
    pages = {}
    for k, (spec, image) in enumerate(images.items()):
        pages[f"pages.{k}"] = image
        for name, array in reference(model, image, device, patch_size).items():
            pages[f"{name}.{k}"] = array
        shape = " x ".join(map(str, image.shape))
        print(f"page {k}: {spec}, {shape}, {pages[f'kept.{k}'].shape[0]} patches kept")
    names = {str(k): spec for k, spec in enumerate(images)}
    save_safetensors(pages_file, pages, {"pages": json.dumps(names)})


TINY_PATCH = 8
TINY_SYMBOLS = ["dot", "bar", "hook", "ring"]
TINY_LINES = ["rule", "arc", "tie"]
TINY_SHAPES = 2


def tiny(out, device):
    """A detector of random weights and two random pages, the fixture of the tests."""
    torch.manual_seed(0)
    backbone = ViT(
        patch_size=TINY_PATCH, dim=16, depth=2, heads=2, mlp_dim=32, channels=3, dim_head=8, use_sdpa=True
    )
    model = OMRDetector(
        backbone,
        num_symbol_classes=len(TINY_SYMBOLS),
        num_line_classes=len(TINY_LINES),
        num_shapes=TINY_SHAPES,
        base_anchor_size=BASE_ANCHOR_SIZE,
    )
    # the norms are born the identity and the biases zero, which would hide a gain or a bias
    # the port forgets: every parameter is moved
    with torch.no_grad():
        for name, p in model.named_parameters():
            if "weighting_fn" not in name:
                p.add_(0.2 * torch.randn_like(p))
    model.eval().to(device)

    rng = np.random.default_rng(0)
    h, w = 20, 27
    rgb = rng.integers(0, 256, (h, w, 3), dtype=np.uint8)
    # flat patches: the second of the first row, the first of the second row, and what
    # the padding repeats of the last column must stay noise
    rgb[0:8, 8:16] = 255
    rgb[8:16, 0:8] = 30
    grey = np.ascontiguousarray(rgb[:, :, 1])
    config = {
        "seed": "0",
        "symbol_classes": json.dumps(TINY_SYMBOLS),
        "line_classes": json.dumps(TINY_LINES),
        "patch_size": str(TINY_PATCH),
        "num_shapes": str(TINY_SHAPES),
        "base_anchor_size": str(BASE_ANCHOR_SIZE),
    }
    export(
        model,
        device,
        config,
        {"random grey": grey, "random rgb": np.ascontiguousarray(rgb)},
        out / "detector_tiny_weights.safetensors",
        out / "detector_tiny_pages.safetensors",
    )


def main():
    here = Path(__file__).resolve().parent
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--checkpoint", type=Path, default=CHECKPOINT)
    parser.add_argument("--annotations", type=Path, default=ANNOTATIONS)
    parser.add_argument("--out", type=Path)
    parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
    parser.add_argument("--tiny", action="store_true", help="the fixture of the tests, of random weights")
    parser.add_argument("pages", nargs="*", default=PAGES)
    args = parser.parse_args()

    if args.tiny:
        tiny(args.out or here.parent / "test", "cpu")
        return
    out = args.out or here

    dataset = parse_coco(args.annotations)
    symbols = [c["name"] for c in dataset.symbol_categories]
    lines = [c["name"] for c in dataset.line_categories]

    model = create_detector(
        backbone_size="nano",
        patch_size=PATCH_SIZE,
        channels=3,
        use_sdpa=True,
        num_symbol_classes=len(symbols),
        num_line_classes=len(lines),
        num_shapes=NUM_SHAPES,
        base_anchor_size=BASE_ANCHOR_SIZE,
    )
    checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=True)
    model.load_state_dict(checkpoint["model"])
    model.eval().to(args.device)

    config = {
        "checkpoint": str(args.checkpoint),
        "symbol_classes": json.dumps(symbols),
        "line_classes": json.dumps(lines),
        "patch_size": str(PATCH_SIZE),
        "num_shapes": str(NUM_SHAPES),
        "base_anchor_size": str(BASE_ANCHOR_SIZE),
    }
    images = {spec: load_page(spec) for spec in args.pages}
    export(
        model,
        args.device,
        config,
        images,
        out / "detector_weights.safetensors",
        out / "detector_pages.safetensors",
    )


if __name__ == "__main__":
    main()
