"""Original valid-convolution U-Net shape demo; no downloaded weights or dataset.

Run: python unet_demo.py
Default channels are narrowed for CPU memory; pass --base-channels 64 to match
Figure 1's channel counts. Both settings retain all four down/up stages.
"""
import argparse
import json
from pathlib import Path

import torch
from torch import nn


def center_crop(feature, target_hw):
    """Align the center of an encoder feature with a decoder feature."""
    height, width = target_hw
    dh = feature.shape[-2] - height
    dw = feature.shape[-1] - width
    if dh < 0 or dw < 0 or dh % 2 or dw % 2:
        raise ValueError('This demo needs a larger, symmetrically croppable skip.')
    top, left = dh // 2, dw // 2
    return feature[..., top:top + height, left:left + width]


class DoubleConv(nn.Module):
    def __init__(
        self, in_channels, out_channels
    ):
        super().__init__()
        self.layers = nn.Sequential(
            nn.Conv2d(
                in_channels, out_channels,
                kernel_size=3, padding=0,
            ),
            nn.ReLU(),
            nn.Conv2d(
                out_channels, out_channels,
                kernel_size=3, padding=0,
            ),
            nn.ReLU(),
        )

    def forward(self, x):
        return self.layers(x)


class UNet(nn.Module):
    def __init__(self, base_channels=8, num_classes=2):
        super().__init__()
        channels = [base_channels * 2**i for i in range(5)]
        inputs = [1] + channels[:-1]
        self.downs = nn.ModuleList(DoubleConv(a, b) for a, b in zip(inputs[:4], channels[:4]))
        self.pool = nn.MaxPool2d(2)
        self.bottleneck = DoubleConv(channels[3], channels[4])
        self.ups = nn.ModuleList(
            nn.ConvTranspose2d(channels[i + 1], channels[i], kernel_size=2, stride=2)
            for i in range(3, -1, -1)
        )
        self.merges = nn.ModuleList(DoubleConv(channels[i] * 2, channels[i]) for i in range(3, -1, -1))
        self.head = nn.Conv2d(channels[0], num_classes, kernel_size=1)

    def forward(self, x, trace=None):
        def record(name, value):
            if trace is not None:
                trace.append({'stage': name, 'shape': list(value.shape)})
        record('input', x)
        skips = []
        for index, down in enumerate(self.downs, 1):
            x = down(x)
            skips.append(x)
            record(f'encoder_{index}', x)
            x = self.pool(x)
            record(f'pool_{index}', x)
        x = self.bottleneck(x)
        record('bottleneck', x)
        for index, (up, merge, skip) in enumerate(zip(self.ups, self.merges, reversed(skips)), 1):
            x = up(x)
            record(f'up_{index}', x)
            skip = center_crop(skip, x.shape[-2:])
            record(f'crop_{index}', skip)
            x = torch.cat([skip, x], dim=1)
            record(f'concat_{index}', x)
            x = merge(x)
            record(f'decoder_{index}', x)
        x = self.head(x)
        record('logits', x)
        return x


def run_demo(base_channels=8):
    torch.manual_seed(7)
    torch.set_num_threads(2)
    model = UNet(base_channels=base_channels)
    # A self-contained, artificial circle example; no real cell image or label.
    y, x = torch.meshgrid(torch.arange(572), torch.arange(572), indexing='ij')
    full_target = (((x - 286)**2 + (y - 286)**2) < 90**2).long()[None]
    image = full_target.float()[:, None] + 0.1 * torch.randn(1, 1, 572, 572)
    trace = []
    logits = model(image, trace=trace)
    assert tuple(logits.shape) == (1, 2, 388, 388)
    # Crop the label to exactly the same center area that the model predicts.
    target = center_crop(full_target, logits.shape[-2:])
    criterion = nn.CrossEntropyLoss()
    # CrossEntropyLoss takes raw logits; do not apply softmax first.
    loss = criterion(logits, target)
    optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
    optimizer.zero_grad()
    loss.backward()
    gradients = [p.grad for p in model.parameters() if p.grad is not None]
    assert gradients and all(torch.isfinite(g).all().item() for g in gradients)
    optimizer.step()
    with torch.no_grad():
        # A separate forward pass after one update; still not a trained model.
        model.eval()
        probabilities = model(image).softmax(dim=1)
        mask = probabilities.argmax(dim=1)
    assert tuple(mask.shape) == (1, 388, 388)
    return {
        'torch_version': torch.__version__, 'device': 'cpu',
        'base_channels': base_channels, 'trace': trace,
        'target_shape': list(target.shape), 'mask_shape': list(mask.shape),
        'target_dtype': str(target.dtype), 'loss_before_one_update': float(loss.detach()),
        'finite_gradients': True, 'parameter_count': sum(p.numel() for p in model.parameters()),
        'training_updates': 1,
        'limits': 'Artificial data, random initialization and one update; not segmentation quality, convergence or a trained checkpoint.',
    }


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--base-channels', type=int, default=8)
    parser.add_argument('--report', type=Path)
    args = parser.parse_args()
    if args.base_channels < 1:
        parser.error('base-channels must be positive')
    result = run_demo(args.base_channels)
    if args.report:
        args.report.parent.mkdir(parents=True, exist_ok=True)
        args.report.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n')
    print(json.dumps(result, ensure_ascii=False, indent=2))
