"""VS2-UNet (public model definition).

Self-contained PyTorch definition of the VS2-UNet architecture used in
"Multi-source conditional information for active-fire discrimination with
VIIRS single-overpass thermal observations" (manuscript in preparation).

The network combines:
  * a thermal UNet trunk operating on 27-channel 64x64 VIIRS windows
    (23 named spectral/thermal channels + 1 night indicator + 3
    persistence-prior channels), and
  * a Sentinel-2 background encoder that maps a 9-band surface-composite
    patch (plus a validity flag) to a 128-d conditioning vector injected
    into the trunk bottleneck through feature-wise linear modulation
    (FiLM: multiplicative gamma and additive beta).

Outputs:
  heatmap logits  - (B, 1, 64, 64) per-pixel fire logits
  objectness logit - (B, 1) window-level fire-presence logit

This file reproduces the trained architecture exactly; load the released
checkpoint `vs2_unet_negcap1_seed42.pt` with
`model.load_state_dict(ckpt["model"])` (strict=True).

License: MIT (see LICENSE_CODE.txt).
"""
import torch
import torch.nn as nn
import torch.nn.functional as F


def cbr(i, o):
    return nn.Sequential(nn.Conv2d(i, o, 3, padding=1), nn.BatchNorm2d(o), nn.SiLU())


def cbm(cin, cout, k=1):
    return nn.Sequential(nn.Conv2d(cin, cout, k, padding=k // 2),
                         nn.BatchNorm2d(cout, eps=1e-3), nn.Mish())


def dwm(c):
    return nn.Sequential(nn.Conv2d(c, c, 3, padding=1, groups=c),
                         nn.BatchNorm2d(c, eps=1e-3), nn.Mish())


class S2Encoder(nn.Module):
    """Sentinel-2 surface encoder (distilled student backbone, heads removed).

    Input: 9-band S2 composite patch normalized with the DynamicWorld-style
    transform (see channel_spec.json / README). The pooled 144-d feature and
    the validity flag are projected to a 128-d conditioning vector for FiLM.

    `ok` is (B, 1): 1.0 when a valid S2 composite is available for the
    window, 0.0 when the S2 input is zero-filled (missing coverage).
    """

    def __init__(self):
        super().__init__()
        self.stem = cbm(9, 64, k=3)
        self.low = nn.Sequential(cbm(64, 48), dwm(48))
        self.b1_main = nn.Sequential(cbm(64, 96), dwm(96), cbm(96, 96), dwm(96),
                                     cbm(96, 96), dwm(96))
        self.b1_skip = cbm(64, 96)
        self.b2_main = nn.Sequential(cbm(96, 144), dwm(144), cbm(144, 144), dwm(144),
                                     cbm(144, 144), dwm(144))
        self.b2_skip = cbm(96, 144)
        self.b3_main = nn.Sequential(cbm(192, 144), dwm(144), cbm(144, 144), dwm(144),
                                     cbm(144, 144), dwm(144))
        self.b3_skip = cbm(192, 144)
        self.proj = nn.Sequential(nn.Linear(144 + 1, 128), nn.SiLU())

    def forward(self, s2, ok):
        x = self.stem(s2)
        x = F.interpolate(x, scale_factor=0.5, mode="bilinear",
                          align_corners=False, antialias=True)
        low = self.low(x)
        y = self.b1_main(x) + self.b1_skip(x)
        y = self.b2_main(y) + self.b2_skip(y)
        y = torch.cat([y, low], 1)
        y = self.b3_main(y) + self.b3_skip(y)
        f = F.adaptive_avg_pool2d(y, 1).flatten(1)  # (B, 144)
        return self.proj(torch.cat([f, ok], 1))  # (B, 128)


class VS2UNet(nn.Module):
    """Thermal trunk + S2-conditional FiLM (released 27-channel NegCap variant).

    forward(x, s2, ok):
        x  - (B, 27, 64, 64) standardized VIIRS window stack
        s2 - (B, 9, 64, 64)  standardized S2 composite patch (zero-filled if absent)
        ok - (B, 1)          S2 validity flag
    returns (heatmap_logits (B,1,64,64), objectness_logit (B,1))
    """

    def __init__(self, cin: int = 27, base: int = 32, use_s2: bool = True):
        super().__init__()
        assert cin == 27, "released checkpoint uses cin=27"
        self.use_s2 = bool(use_s2)
        self.e1 = cbr(cin, base)
        self.e2 = cbr(base, base * 2)
        self.e3 = cbr(base * 2, base * 4)
        self.bott = cbr(base * 4, base * 4)
        self.pool = nn.MaxPool2d(2)
        self.up = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)
        self.d3 = cbr(base * 4 + base * 4, base * 2)
        self.d2 = cbr(base * 2 + base * 2, base)
        self.d1 = cbr(base + base, base)
        self.head = nn.Conv2d(base, 1, 1)
        self.obj = nn.Sequential(nn.AdaptiveAvgPool2d(1), nn.Flatten(),
                                 nn.Linear(base * 4, 1))
        self.s2enc = S2Encoder() if use_s2 else None
        self.film = nn.Linear(128, base * 4 * 2) if use_s2 else None

    def forward(self, x, s2, ok):
        c1 = self.e1(x)
        c2 = self.e2(self.pool(c1))
        c3 = self.e3(self.pool(c2))
        b = self.bott(self.pool(c3))
        if self.use_s2:
            g, be = self.film(self.s2enc(s2, ok)).chunk(2, 1)
            b = b * (1 + g[..., None, None]) + be[..., None, None]
        o = self.obj(b)
        u3 = self.d3(torch.cat([self.up(b), c3], 1))
        u2 = self.d2(torch.cat([self.up(u3), c2], 1))
        u1 = self.d1(torch.cat([self.up(u2), c1], 1))
        return self.head(u1), o


def load_release_checkpoint(path, device="cpu"):
    """Load the released checkpoint into a VS2UNet and return (model, meta)."""
    ck = torch.load(path, map_location=device, weights_only=False)
    model = VS2UNet(cin=ck["config"]["cin"], base=ck["config"]["base"],
                    use_s2=ck["config"]["use_s2"])
    model.load_state_dict(ck["model"], strict=True)
    model.eval()
    return model, ck
