# Copyright (c) 2025, NVIDIA CORPORATION.  All rights reserved.
#
# 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 nemo_run as run
import pytest

from nemo.collections.llm.api import finetune, pretrain
from nemo.collections.llm.gpt.data.mock import MockDataModule
from nemo.collections.llm.gpt.data.packed_sequence import PackedSequenceSpecs
from nemo.collections.llm.gpt.data.squad import SquadDataModule
from nemo.collections.llm.gpt.model.phi3mini import Phi3ConfigMini, Phi3Model
from nemo.collections.llm.peft import PEFT_STR2CLS
from nemo.collections.llm.recipes import phi3_mini_4k_instruct
from nemo.lightning import Trainer


class TestPhi3Mini4kInstruct:
    @pytest.fixture(scope="class")
    def recipe_module(self):
        return phi3_mini_4k_instruct

    def test_model(self, recipe_module):
        model_config = recipe_module.model()
        assert isinstance(model_config, run.Config)
        assert model_config.__fn_or_cls__ == Phi3Model
        assert isinstance(model_config.config, run.Config)
        assert model_config.config.__fn_or_cls__ == Phi3ConfigMini

    def test_trainer_default_settings(self, recipe_module):
        trainer = recipe_module.trainer()
        assert isinstance(trainer, run.Config)
        assert trainer.__fn_or_cls__ == Trainer

        # Check default parallelism settings
        assert trainer.strategy.tensor_model_parallel_size == 1
        assert trainer.strategy.pipeline_model_parallel_size == 1
        assert trainer.strategy.pipeline_dtype is None
        assert trainer.strategy.virtual_pipeline_model_parallel_size is None
        assert trainer.strategy.context_parallel_size == 1
        assert trainer.strategy.sequence_parallel is False

        # Check default training settings
        assert trainer.max_steps == 1168251
        assert trainer.accumulate_grad_batches == 1
        assert trainer.limit_test_batches == 50
        assert trainer.limit_val_batches == 32
        assert trainer.log_every_n_steps == 10
        assert trainer.val_check_interval == 2000
        assert trainer.num_nodes == 1
        assert trainer.devices == 1

        # Check DDP settings
        assert trainer.strategy.ddp.check_for_nan_in_grad is True
        assert trainer.strategy.ddp.grad_reduce_in_fp32 is True
        assert trainer.strategy.ddp.overlap_grad_reduce is True
        assert trainer.strategy.ddp.overlap_param_gather is True
        assert trainer.strategy.ddp.average_in_collective is True

    def test_pretrain_recipe(self, recipe_module):
        recipe = recipe_module.pretrain_recipe()
        assert isinstance(recipe, run.Partial)
        assert recipe.__fn_or_cls__ == pretrain

        # Check model configuration
        assert isinstance(recipe.model, run.Config)
        assert recipe.model.__fn_or_cls__ == Phi3Model

        # Check data configuration
        assert isinstance(recipe.data, run.Config)
        assert recipe.data.__fn_or_cls__ == MockDataModule
        assert recipe.data.seq_length == 4096
        assert recipe.data.global_batch_size == 512
        assert recipe.data.micro_batch_size == 1

    def test_finetune_recipe(self, recipe_module):
        recipe = recipe_module.finetune_recipe()
        assert isinstance(recipe, run.Partial)
        assert recipe.__fn_or_cls__ == finetune
        assert isinstance(recipe.model, run.Config)
        assert recipe.model.__fn_or_cls__ == Phi3Model
        assert isinstance(recipe.trainer, run.Config)
        assert recipe.trainer.__fn_or_cls__ == Trainer
        assert isinstance(recipe.data, run.Config)
        assert recipe.data.__fn_or_cls__ == SquadDataModule

        # Check PEFT configuration
        assert isinstance(recipe.peft, run.Config)
        assert recipe.peft.__fn_or_cls__ == PEFT_STR2CLS['lora']
        assert recipe.peft.dim == 8
        assert recipe.peft.alpha == 16
        assert recipe.optim.config.lr == 1e-4

    def test_finetune_recipe_with_dora(self, recipe_module):
        recipe = recipe_module.finetune_recipe(peft_scheme='dora')
        assert isinstance(recipe.peft, run.Config)
        assert recipe.peft.__fn_or_cls__ == PEFT_STR2CLS['dora']
        assert recipe.peft.dim == 8
        assert recipe.peft.alpha == 16
        assert recipe.optim.config.lr == 1e-4

    def test_finetune_recipe_without_peft(self, recipe_module):
        recipe = recipe_module.finetune_recipe(peft_scheme=None)
        assert not hasattr(recipe, 'peft') or recipe.peft is None
        assert recipe.trainer.strategy.tensor_model_parallel_size == 1
        assert recipe.optim.config.lr == 5e-6

    def test_finetune_recipe_with_invalid_peft(self, recipe_module):
        with pytest.raises(ValueError, match="Unrecognized peft scheme: invalid_scheme"):
            recipe_module.finetune_recipe(peft_scheme="invalid_scheme")

    def test_finetune_recipe_with_packed_sequence(self, recipe_module):
        recipe = recipe_module.finetune_recipe(packed_sequence=True)
        assert recipe.data.seq_length == 4096
        assert isinstance(recipe.data.packed_sequence_specs, run.Config)
        assert recipe.data.packed_sequence_specs.__fn_or_cls__ == PackedSequenceSpecs
        assert recipe.data.packed_sequence_specs.packed_sequence_size == 4096
