# examples/simclr_training.py
"""Reduced SimCLR mechanics on CPU; no pretrained weights or benchmark claims.

Run --smoke for an offline update, or --export DIR to inspect licensed local
photographs. The encoder is a small CNN, not the paper's ResNet-50. The head
keeps nonlinear projection and BN; SGD replaces distributed LARS.
"""

import argparse
import hashlib
import json
import math
import platform
from pathlib import Path

from PIL import Image, __version__ as pillow_version
import torch
from torch import nn
from torch.nn import functional as F
import torchvision
from torchvision import transforms


# region: views
def two_views(images, size=32):
    """Draw independent crop/color/blur transformations for every RGB image."""
    if not images or not isinstance(size, int) or size < 8:
        raise ValueError("Provide images and a crop size of at least 8.")
    transform = transforms.Compose(
        [
            transforms.RandomResizedCrop(
                size,
                scale=(0.08, 1.0),
                interpolation=transforms.InterpolationMode.BICUBIC,
            ),
            transforms.RandomHorizontalFlip(),
            transforms.RandomApply(
                [transforms.ColorJitter(0.8, 0.8, 0.8, 0.2)], p=0.8
            ),
            transforms.RandomGrayscale(p=0.2),
            transforms.RandomApply(
                [transforms.GaussianBlur(3, sigma=(0.1, 2.0))], p=0.5
            ),
            transforms.ToTensor(),
        ]
    )
    first = torch.stack([transform(image.convert("RGB")) for image in images])
    second = torch.stack([transform(image.convert("RGB")) for image in images])
    return first, second


# endregion: views


# region: encoder
class SimCLR(nn.Module):
    """Share one reduced encoder and one nonlinear head across both views."""

    def __init__(self, representation_dim=32, projection_dim=16):
        super().__init__()
        if any(
            not isinstance(dim, int) or dim < 1
            for dim in (representation_dim, projection_dim)
        ):
            raise ValueError("Feature dimensions must be positive.")
        self.encoder = nn.Sequential(
            nn.Conv2d(3, 16, 3, padding=1),
            nn.ReLU(),
            nn.Conv2d(16, representation_dim, 3, stride=2, padding=1),
            nn.ReLU(),
            nn.AdaptiveAvgPool2d(1),
            nn.Flatten(),
        )
        self.head = nn.Sequential(
            nn.Linear(representation_dim, representation_dim, bias=False),
            nn.BatchNorm1d(representation_dim),
            nn.ReLU(),
            nn.Linear(representation_dim, projection_dim, bias=False),
            nn.BatchNorm1d(projection_dim, affine=False),
        )

    def forward(self, views):
        if views.ndim != 4 or views.shape[1] != 3 or min(views.shape[2:]) < 8:
            raise ValueError("Expected [B, 3, H, W] with H and W at least 8.")
        h = self.encoder(views)
        return h, self.head(h)


# endregion: encoder


# region: normalize
def normalized_similarity(z):
    """Return cosine similarities after checking nonzero finite embeddings."""
    if z.ndim != 2 or z.shape[0] < 4 or z.shape[0] % 2 or z.shape[1] < 1:
        raise ValueError("Expected [2N, D] with N >= 2 and D >= 1.")
    if not torch.is_floating_point(z) or not torch.isfinite(z).all():
        raise ValueError("Embeddings must be finite floating-point values.")
    if torch.any(z.norm(dim=1) <= 1e-12):
        raise ValueError("Cosine similarity requires nonzero embeddings.")
    unit_z = F.normalize(z, dim=1)
    return unit_z @ unit_z.T


# endregion: normalize


# region: positives
def positive_indices(batch_size, device=None):
    """Map [all first views, all second views] to the other view of each image."""
    if not isinstance(batch_size, int) or batch_size < 2:
        raise ValueError("At least two images are required for negatives.")
    indices = torch.arange(2 * batch_size, device=device)
    return (indices + batch_size) % (2 * batch_size)


# endregion: positives


# region: mask
def contrastive_logits(z, temperature=0.1):
    """Exclude only self-similarity; the positive remains in the denominator."""
    if not math.isfinite(temperature) or temperature <= 0:
        raise ValueError("Temperature must be finite and positive.")
    similarity = normalized_similarity(z)
    logits = similarity / temperature
    self_mask = torch.eye(z.shape[0], dtype=torch.bool, device=z.device)
    return logits.masked_fill(self_mask, -torch.inf)


# endregion: mask


# region: loss
def nt_xent(z, temperature=0.1, reduction="mean"):
    """Average both positive directions as in Algorithm 1, not just one half."""
    logits = contrastive_logits(z, temperature)
    targets = positive_indices(z.shape[0] // 2, z.device)
    return F.cross_entropy(logits, targets, reduction=reduction)


# endregion: loss


# region: update
def train_step(model, optimizer, first, second, temperature=0.1):
    """Update the same encoder and head jointly from both view branches."""
    if first.ndim != 4 or first.shape != second.shape or first.shape[0] < 2:
        raise ValueError(
            "Both view batches must have matching shapes and N >= 2."
        )
    model.train()
    optimizer.zero_grad(set_to_none=True)
    h, z = model(torch.cat([first, second], dim=0))
    loss = nt_xent(z, temperature)
    loss.backward()
    optimizer.step()
    return {
        "loss": loss.item(),
        "h_shape": list(h.shape),
        "z_shape": list(z.shape),
    }


# endregion: update


# region: frozen
def linear_probe_step(encoder, classifier, optimizer, images, labels):
    """Train only a classifier on h; freeze parameters and BN statistics."""
    if images.ndim != 4 or images.shape[1] != 3 or min(images.shape[2:]) < 8:
        raise ValueError("Expected images [B, 3, H, W], H and W at least 8.")
    if (
        labels.ndim != 1
        or labels.shape[0] != images.shape[0]
        or labels.dtype != torch.long
    ):
        raise ValueError("Labels must be int64 [B] matching the image batch.")
    encoder.requires_grad_(False)
    encoder.zero_grad(set_to_none=True)
    encoder.eval()
    classifier.train()
    with torch.no_grad():
        h = encoder(images)
    logits = classifier(h)
    if torch.any(labels < 0) or torch.any(labels >= logits.shape[1]):
        raise ValueError("Labels must index the classifier classes.")
    optimizer.zero_grad(set_to_none=True)
    loss = F.cross_entropy(logits, labels)
    loss.backward()
    optimizer.step()
    return loss.item()


# endregion: frozen


def smoke():
    """Check one update with synthetic inputs, without files or downloads."""
    torch.manual_seed(7)
    model = SimCLR()
    first, second = torch.rand(4, 3, 32, 32), torch.rand(4, 3, 32, 32)
    optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
    result = train_step(model, optimizer, first, second)
    result["scope"] = "Reduced random-weight CPU mechanics; synthetic inputs."
    result["seed"] = 7
    return result


def export_inspection(output, photo_root):
    """Save deterministic real-image views and their random-weight loss terms."""
    torch.manual_seed(7)
    photo_root, output = Path(photo_root), Path(output)
    manifest = json.loads((photo_root / "predictions.json").read_text())
    photos = manifest["photos"]
    images = []
    for photo in photos:
        source = photo_root / photo["originalImage"]
        if (
            hashlib.sha256(source.read_bytes()).hexdigest()
            != photo["source"]["sha256"]
        ):
            raise ValueError(f"Source image hash mismatch: {source}")
        with Image.open(source) as image:
            images.append(image.convert("RGB"))
    first, second = two_views(images)
    model = SimCLR()
    # No update: BN uses this complete small batch, with random initialized weights.
    model.train()
    with torch.no_grad():
        h, z = model(torch.cat([first, second]))
        similarity = normalized_similarity(z)
        terms = nt_xent(z, reduction="none")
        logits = contrastive_logits(z)
        probability = logits.softmax(dim=1)
    output.mkdir(parents=True, exist_ok=True)
    saved_photos = []
    for index, photo in enumerate(photos):
        views = []
        for name, batch in [("first", first), ("second", second)]:
            filename = f'{photo["id"]}-{name}.png'
            transforms.ToPILImage()(batch[index]).save(output / filename)
            views.append(
                {
                    "file": filename,
                    "sha256": hashlib.sha256(
                        (output / filename).read_bytes()
                    ).hexdigest(),
                }
            )
        saved_photos.append(
            {
                "id": photo["id"],
                "title": photo["title"],
                "source": photo["source"],
                "views": views,
            }
        )
    result = {
        "scope": "Real photographs; reduced randomly initialized CNN; no pretraining or semantic evaluation.",
        "seed": 7,
        "temperature": 0.1,
        "photos": saved_photos,
        "order": [f'{p["id"]}-first' for p in photos]
        + [f'{p["id"]}-second' for p in photos],
        "positives": positive_indices(len(images)).tolist(),
        "similarity": similarity.tolist(),
        "lossTerms": terms.tolist(),
        "positiveProbabilities": probability[
            torch.arange(len(terms)), positive_indices(len(images))
        ].tolist(),
        "loss": terms.mean().item(),
        "hShape": list(h.shape),
        "zShape": list(z.shape),
        "provenance": {
            "architecture": "Conv3x3(3,16), ReLU, Conv3x3s2(16,32), ReLU, GAP; head 32->32->16 with BN/ReLU",
            "checkpoint": None,
            "officialRevision": "383d4143fd8cf7879ae10f1046a9baeb753ff438",
            "source": "https://github.com/google-research/simclr",
            "python": platform.python_version(),
            "torch": torch.__version__,
            "torchvision": torchvision.__version__,
            "pillow": pillow_version,
            "threads": torch.get_num_threads(),
            "device": "cpu",
            "programSha256": hashlib.sha256(
                Path(__file__).read_bytes()
            ).hexdigest(),
            "command": "python examples/simclr_training.py --export public/examples/simclr-demo",
            "preprocessing": "RGB; independent bicubic random-resized 32px crop scale .08..1 ratio .75..1.333; flip .5; color jitter (.8,.8,.8,.2) probability .8; grayscale .2; Gaussian blur kernel3 sigma .1..2 probability .5; ToTensor [0,1]; no channel normalization.",
        },
    }
    (output / "inspection.json").write_text(json.dumps(result, indent=2) + "\n")
    return {
        "loss": result["loss"],
        "photos": len(images),
        "output": str(output),
    }


def main():
    """Run offline mechanics or an explicitly requested local-photo export."""
    parser = argparse.ArgumentParser(description=__doc__)
    mode = parser.add_mutually_exclusive_group(required=True)
    mode.add_argument("--smoke", action="store_true")
    mode.add_argument("--export", type=Path)
    parser.add_argument(
        "--photo-root", type=Path, default=Path("public/examples/vit-demo")
    )
    args = parser.parse_args()
    torch.set_num_threads(2)
    result = (
        smoke()
        if args.smoke
        else export_inspection(args.export, args.photo_root)
    )
    print(json.dumps(result))


if __name__ == "__main__":
    main()
