# Copyright 2026 AlQuraishi Laboratory
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import unittest

import numpy as np
import torch

from openfold3.core.model.heads.head_modules import AuxiliaryHeadsAllAtom
from openfold3.core.model.heads.prediction_heads import (
    ExperimentallyResolvedHeadAllAtom,
    PairformerEmbedding,
    PerResidueLDDTAllAtom,
    PredictedAlignedErrorHead,
    PredictedDistanceErrorHead,
)
from openfold3.core.utils.atomize_utils import broadcast_token_feat_to_atoms
from openfold3.projects.of3_all_atom.config.model_config import (
    max_atoms_per_token,
)
from openfold3.projects.of3_all_atom.project_entry import OF3ProjectEntry
from openfold3.tests.config import consts
from openfold3.tests.data_utils import random_of3_features


class TestPredictedAlignedErrorHead(unittest.TestCase):
    def test_predicted_aligned_error_head_shape(self):
        batch_size = consts.batch_size
        n_token = consts.n_res
        c_z = consts.c_z
        c_out = 50

        pae_head = PredictedAlignedErrorHead(c_z, c_out)

        zij = torch.ones((batch_size, n_token, n_token, c_z))
        out = pae_head(zij)

        expected_shape = (batch_size, n_token, n_token, c_out)
        np.testing.assert_array_equal(out.shape, expected_shape)


class TestPredictedDistanceErrorHead(unittest.TestCase):
    def test_predicted_distance_error_head_shape(self):
        batch_size = consts.batch_size
        n_token = consts.n_res
        c_z = consts.c_z
        c_out = 50

        pde_head = PredictedDistanceErrorHead(c_z, c_out)

        zij = torch.ones((batch_size, n_token, n_token, c_z))
        out = pde_head(zij)

        expected_shape = (batch_size, n_token, n_token, c_out)
        np.testing.assert_array_equal(out.shape, expected_shape)


class TestPLDDTHead(unittest.TestCase):
    def test_plddt_head_shape(self):
        batch_size = consts.batch_size
        n_token = consts.n_res
        c_s = consts.c_s
        c_out = 50

        plddt_head = PerResidueLDDTAllAtom(
            c_s, c_out, max_atoms_per_token=max_atoms_per_token.get()
        )

        si = torch.ones((batch_size, n_token, c_s))
        token_mask = torch.ones((batch_size, n_token))
        num_atoms_per_token = torch.randint(
            0, max_atoms_per_token.get(), (batch_size, n_token)
        )
        n_atom = torch.max(torch.sum(num_atoms_per_token, dim=-1)).int().item()

        max_atom_per_token_mask = broadcast_token_feat_to_atoms(
            token_mask=token_mask,
            num_atoms_per_token=num_atoms_per_token,
            token_feat=token_mask,
            max_num_atoms_per_token=max_atoms_per_token.get(),
        )

        out = plddt_head(s=si, max_atom_per_token_mask=max_atom_per_token_mask)

        expected_shape = (batch_size, n_atom, c_out)
        np.testing.assert_array_equal(out.shape, expected_shape)


class TestExperimentallyResolvedHeadAllAtom(unittest.TestCase):
    def test_experimentally_resolved_head_all_atom_shape(self):
        batch_size = consts.batch_size
        n_token = consts.n_res
        c_s = consts.c_s
        c_out = 50

        exp_res_head = ExperimentallyResolvedHeadAllAtom(
            c_s, c_out, max_atoms_per_token=max_atoms_per_token.get()
        )

        si = torch.ones((batch_size, n_token, c_s))
        token_mask = torch.ones((batch_size, n_token))
        num_atoms_per_token = torch.randint(
            0, max_atoms_per_token.get(), (batch_size, n_token)
        )
        n_atom = torch.max(torch.sum(num_atoms_per_token, dim=-1)).int().item()

        max_atom_per_token_mask = broadcast_token_feat_to_atoms(
            token_mask=token_mask,
            num_atoms_per_token=num_atoms_per_token,
            token_feat=token_mask,
            max_num_atoms_per_token=max_atoms_per_token.get(),
        )

        out = exp_res_head(s=si, max_atom_per_token_mask=max_atom_per_token_mask)

        expected_shape = (batch_size, n_atom, c_out)
        np.testing.assert_array_equal(out.shape, expected_shape)


class TestPairformerEmbedding(unittest.TestCase):
    def test_pairformer_embedding_shape(self):
        batch_size = consts.batch_size
        n_token = consts.n_res

        proj_entry = OF3ProjectEntry()
        config = proj_entry.get_model_config_with_presets()

        c_s_input = config.architecture.shared.c_s_input
        c_s = config.architecture.shared.c_s
        c_z = config.architecture.shared.c_z

        pair_emb = PairformerEmbedding(
            **config.architecture.heads.pairformer_embedding
        ).eval()

        si_input = torch.ones(batch_size, n_token, c_s_input)
        si = torch.ones(batch_size, n_token, c_s)
        zij = torch.ones(batch_size, n_token, n_token, c_z)
        atom_positions_predicted = torch.ones(batch_size, n_token, 3)
        single_mask = torch.randint(
            0,
            2,
            size=(
                batch_size,
                n_token,
            ),
        )
        pair_mask = torch.randint(0, 2, size=(batch_size, n_token, n_token))

        out_single, out_pair = pair_emb(
            si_input,
            si,
            zij,
            atom_positions_predicted,
            single_mask,
            pair_mask,
            chunk_size=4,
        )

        expected_shape_single = (batch_size, n_token, c_s)
        np.testing.assert_array_equal(out_single.shape, expected_shape_single)

        expected_shape_pair = (batch_size, n_token, n_token, c_z)
        np.testing.assert_array_equal(out_pair.shape, expected_shape_pair)


class TestAuxiliaryHeadsAllAtom(unittest.TestCase):
    def test_auxiliary_heads_all_atom_shape(self):
        batch_size = consts.batch_size
        n_token = consts.n_res
        n_msa = 10
        n_templ = 3

        proj_entry = OF3ProjectEntry()
        config = proj_entry.get_model_config_with_presets()

        c_s_input = config.architecture.shared.c_s_input
        c_s = config.architecture.shared.c_s
        c_z = config.architecture.shared.c_z

        batch = random_of3_features(
            batch_size=batch_size, n_token=n_token, n_msa=n_msa, n_templ=n_templ
        )
        n_atom = torch.max(batch["num_atoms_per_token"].sum(dim=-1)).int().item()

        heads_config = config.architecture.heads
        heads_config.pae.enabled = True
        aux_head = AuxiliaryHeadsAllAtom(heads_config).eval()

        si_input = torch.ones(batch_size, n_token, c_s_input)
        si = torch.ones(batch_size, n_token, c_s)
        zij = torch.ones(batch_size, n_token, n_token, c_z)
        atom_positions_predicted = torch.randn(batch_size, n_atom, 3)

        outputs = {
            "si_trunk": si,
            "zij_trunk": zij,
            "atom_positions_predicted": atom_positions_predicted,
        }

        aux_out = aux_head(
            batch,
            si_input,
            outputs,
            use_zij_trunk_embedding=True,
            chunk_size=4,
        )

        expected_shape_distogram = (
            batch_size,
            n_token,
            n_token,
            heads_config.distogram.c_out,
        )
        np.testing.assert_array_equal(
            aux_out["distogram_logits"].shape, expected_shape_distogram
        )

        expected_shape_pae = (batch_size, n_token, n_token, heads_config.pae.c_out)
        np.testing.assert_array_equal(aux_out["pae_logits"].shape, expected_shape_pae)

        expected_shape_pde = (batch_size, n_token, n_token, heads_config.pde.c_out)
        np.testing.assert_array_equal(aux_out["pde_logits"].shape, expected_shape_pde)

        expected_shape_plddt = (batch_size, n_atom, heads_config.lddt.c_out)
        np.testing.assert_array_equal(
            aux_out["plddt_logits"].shape, expected_shape_plddt
        )

        expected_shape_exp_res = (
            batch_size,
            n_atom,
            heads_config.experimentally_resolved.c_out,
        )
        np.testing.assert_array_equal(
            aux_out["experimentally_resolved_logits"].shape, expected_shape_exp_res
        )


if __name__ == "__main__":
    unittest.main()
