# 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.

from dataclasses import dataclass

from loguru import logger

from nemo_curator.stages.base import ProcessingStage
from nemo_curator.tasks import DocumentBatch


@dataclass
class AddId(ProcessingStage[DocumentBatch, DocumentBatch]):
    """
    The module responsible for adding unique IDs to each document record.

    This stage adds a unique identifier to each document in the batch by combining
    the task UUID with a sequential index.

    Args:
        id_field (str): The field where the generated ID will be stored.
        id_prefix (str | None): A prefix to add to the generated IDs.
        overwrite (bool): Whether to overwrite existing IDs.
    """

    id_field: str
    id_prefix: str | None = None
    overwrite: bool = False
    _name: str = "add_id"

    def inputs(self) -> tuple[list[str], list[str]]:
        return ["data"], []

    def outputs(self) -> tuple[list[str], list[str]]:
        return ["data"], [self.id_field]

    def process(self, batch: DocumentBatch) -> DocumentBatch | None:
        """
        Adds unique IDs to each document in the batch.

        The IDs are generated by combining the batch UUID with a sequential index,
        ensuring uniqueness across the entire dataset.

        Args:
            batch (DocumentBatch): The batch to add IDs to

        Returns:
            DocumentBatch: A batch with unique IDs added to each document
        """
        df = batch.to_pandas()

        # If column already exists, decide how to handle it
        if self.id_field in df.columns:
            if self.overwrite:
                logger.warning(f"Column '{self.id_field}' already exists and will be overwritten.")
            else:
                msg = f"Column '{self.id_field}' already exists. Set overwrite=True to replace it."
                raise ValueError(msg)

        uuid_part = str(batch._uuid)
        prefix = f"{self.id_prefix}_{uuid_part}" if self.id_prefix else uuid_part

        df[self.id_field] = [f"{prefix}_{i}" for i in range(len(df))]
        # Create output batch
        return DocumentBatch(
            task_id=f"{batch.task_id}_{self.name}",
            dataset_name=batch.dataset_name,
            data=df,
            _metadata=batch._metadata,
            _stage_perf=batch._stage_perf,
        )
