import logging
import multiprocessing
import os
from contextlib import nullcontext

from trl.commands.cli_utils import DPOScriptArguments, init_zero_verbose, TrlParser
from trl.env_utils import strtobool
from peft import PeftModel
TRL_USE_RICH = strtobool(os.getenv("TRL_USE_RICH", "0"))

if TRL_USE_RICH:
    init_zero_verbose()
    FORMAT = "%(message)s"

    from rich.console import Console
    from rich.logging import RichHandler

import torch
from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer

from trl import (
    KTOConfig,
    KTOTrainer,
    ModelConfig,
    RichProgressCallback,
    get_kbit_device_map,
    get_peft_config,
    get_quantization_config,
)

import tempfile
import os
from fastchat.train.my_hdfs_io import hcopy, hmkdir
def load_hdfs_path(ckpt_path):
    if ckpt_path.startswith("hdfs"):
        tmp_dir = os.path.join(
            tempfile.gettempdir(), os.path.basename(ckpt_path)
        )
        local_dir = tmp_dir
        hcopy(ckpt_path, local_dir)
    else:
        local_dir = ckpt_path
    return local_dir


local_rank = None

if TRL_USE_RICH:
    logging.basicConfig(format=FORMAT, datefmt="[%X]", handlers=[RichHandler()], level=logging.INFO)

def rank0_init_wandb(task_name = "tinyllama-code-kto"):
    if local_rank == 0:
        import wandb
        wandb.init(project="....fschat", name=task_name, notes=task_name)


from dataclasses import dataclass, field
@dataclass
class CustomArguments(DPOScriptArguments):
    my_task_name: str = field(default="tinyllama-code-kto", metadata={"help": "Description of my task name for wandb"})
    save_hdfs_path: str = field(default="....../home/.../.../user/.../metadata/generate/tmp", metadata={"help": "save hdfs path"})
    load_lora_local_path: str = field(default="", metadata={"help": "load lora local path"})




from typing import Any, Dict, List, Optional, TypeVar

from datasets import Dataset, DatasetDict
from transformers import PreTrainedTokenizer


DatasetType = TypeVar("DatasetType", Dataset, DatasetDict)
def _unpair_row(examples: List[Dict[str, List[Dict[str, str]]]]) -> List[Dict[str, List[Dict[str, str]]]]:
    batch_size = len(examples["chosen"])
    new_rows = {
        "completion": examples["chosen"] + examples["rejected"],
        "label": [True] * batch_size + [False] * batch_size,
    }
    if "prompt" in examples:
        new_rows["prompt"] = examples["prompt"] + examples["prompt"]
    return new_rows


def unpair_preference_dataset(dataset: DatasetType, num_proc: Optional[int] = None) -> DatasetType:
    r"""
    Unpair a preference dataset.

    Args:
        dataset (`Dataset` or `DatasetDict`):
            Preference dataset to unpair. The dataset must have columns `"chosen"`, `"rejected"` and ...ionally
            `"prompt"`.
        num_proc (`Optional[int]`, *...ional*, defaults to `None`):
            Number of processes to use for processing the dataset.

    Returns:
        `Dataset`: The unpaired preference dataset.

    Example:

    ```python
    >>> from datasets import Dataset
    >>> dataset_dict = {
    ...     "prompt": ["The sky is", "The sun is"]
    ...     "chosen": [" blue.", "in the sky."],
    ...     "rejected": [" green.", " in the sea."]
    ... }
    >>> dataset = Dataset.from_dict(dataset_dict)
    >>> dataset = unpair_preference_dataset(dataset)
    >>> dataset
    Dataset({
        features: ['prompt', 'completion', 'label'],
        num_rows: 4
    })
    >>> dataset[0]
    {'prompt': 'The sky is', 'completion': ' blue.', 'label': True}
    ```
    """
    return dataset.map(_unpair_row, batched=True, remove_columns=["chosen", "rejected"], num_proc=num_proc)


def maybe_unpair_preference_dataset(dataset: DatasetType, num_proc: Optional[int] = None) -> DatasetType:
    r"""
    Unpair a preference dataset if it is paired.

    Args:
        dataset (`Dataset` or `DatasetDict`):
            Preference dataset to unpair. The dataset must have columns `"chosen"`, `"rejected"` and ...ionally
            `"prompt"`.
        num_proc (`Optional[int]`, *...ional*, defaults to `None`):
            Number of processes to use for processing the dataset.

    Returns:
        `Dataset` or `DatasetDict`: The unpaired preference dataset if it was paired, otherwise the original dataset.

    Example:

    ```python
    >>> from datasets import Dataset
    >>> dataset_dict = {
    ...     "prompt": ["The sky is", "The sun is"]
    ...     "chosen": [" blue.", "in the sky."],
    ...     "rejected": [" green.", " in the sea."]
    ... }
    >>> dataset = Dataset.from_dict(dataset_dict)
    >>> dataset = unpair_preference_dataset(dataset)
    >>> dataset
    Dataset({
        features: ['prompt', 'completion', 'label'],
        num_rows: 4
    })
    >>> dataset[0]
    {'prompt': 'The sky is', 'completion': ' blue.', 'label': True}
    ```
    """
    if isinstance(dataset, DatasetDict):
        column_names = dataset[list(dataset.keys())[0]].column_names
    else:
        column_names = dataset.column_names
    if "chosen" in column_names and "rejected" in column_names:
        return unpair_preference_dataset(dataset, num_proc=num_proc)
    else:
        return dataset

if __name__ == "__main__":
    parser = TrlParser((CustomArguments, KTOConfig, ModelConfig))
    args, training_args, model_config = parser.parse_args_and_config()
    model_config.model_name_or_path = load_hdfs_path(model_config.model_name_or_path)
    args.dataset_name = load_hdfs_path(args.dataset_name)

    print("args:", args)
    print("training_args:", training_args)
    print("model_config:", model_config)

    local_rank = training_args.local_rank
    rank0_init_wandb(args.my_task_name)

    if TRL_USE_RICH:
        training_args.disable_tqdm = True
        console = Console()

    torch_dtype = (
        model_config.torch_dtype
        if model_config.torch_dtype in ["auto", None]
        else getattr(torch, model_config.torch_dtype)
    )
    quantization_config = get_quantization_config(model_config)
    model_kwargs = dict(
        revision=model_config.model_revision,
        trust_remote_code=model_config.trust_remote_code,
        attn_implementation=model_config.attn_implementation,
        torch_dtype=torch_dtype,
        use_cache=False if training_args.gradient_checkpointing else True,
        device_map=get_kbit_device_map() if quantization_config is not None else None,
        quantization_config=quantization_config,
    )
    model = AutoModelForCausalLM.from_pretrained(model_config.model_name_or_path, **model_kwargs)

    if args.load_lora_local_path and args.load_lora_local_path.strip():
        from peft import PeftModel

        model = PeftModel.from_pretrained(model, args.load_lora_local_path)
        print("[LoRA] Loaded PEFT model. Merging...")
        model.merge_and_unload()
        print("[LoRA] Merge complete.")


    model_config.lora_target_modules=[
            "q_proj",
            "o_proj",
            "k_proj",
            "v_proj",
            "gate_proj",
            "up_proj",
            "down_proj",
        ]
    peft_config = get_peft_config(model_config)
    if peft_config is None:
        model_ref = AutoModelForCausalLM.from_pretrained(model_config.model_name_or_path, **model_kwargs)
    else:
        model_ref = None
    tokenizer = AutoTokenizer.from_pretrained(model_config.model_name_or_path)
    if tokenizer.pad_token is None:
        tokenizer.pad_token = tokenizer.eos_token
    if tokenizer.chat_template is None:
        tokenizer.chat_template = "{% for message in messages %}{{message['role'] + ': ' + message['content'] + '\n\n'}}{% endfor %}{{ eos_token }}"
    if args.ignore_bias_buffers:
        model._ddp_params_and_buffers_to_ignore = [
            name for name, buffer in model.named_buffers() if buffer.dtype == torch.bool
        ]

    init_context = nullcontext() if not TRL_USE_RICH else console.status("[bold green]Initializing the KTOTrainer...")
    save_context = (
        nullcontext()
        if not TRL_USE_RICH
        else console.status(f"[bold green]Training completed! Saving the model to {training_args.output_dir}")
    )

    import json
    ds = load_dataset("json",data_files=args.dataset_name)['train']
    if args.sanity_check:
        for key in ds:
            ds[key] = ds[key].select(range(50))

    def process(row):
        row['prompt'] = row['prompt']
        row['chosen'] = row['ranked_code'][0]
        row['rejected'] = row['ranked_code'][-1]
        if len(row['prompt']) == 0:
            row['prompt'] = ' '
            print("[FIX] prompt len = 0")
        if len(row['chosen']) == 0:
            row['chosen'] = ' '
            print("[FIX] chosen len = 0")
        if len(row['rejected']) == 0:
            row['rejected'] = ' '
            print("[FIX] rejected len = 0")

        return row

    ds = ds.map(
        process,
        num_proc=multiprocessing.cpu_count(),
        load_from_cache_file=False,
    )
    ds = ds.remove_columns(['task_id', 'ranked_code', 'chose_code', 'rejected_code', 'ranked_test'])

    print(ds)

    ds = maybe_unpair_preference_dataset(ds)

    print(ds)

    ds = ds.train_test_split(test_size=0.01)
    train_dataset = ds['train']
    eval_dataset = ds['test']

    with init_context:
        trainer = KTOTrainer(
            model,
            model_ref,
            args=training_args,
            train_dataset=train_dataset,
            eval_dataset=eval_dataset,
            tokenizer=tokenizer,
            peft_config=peft_config,
            callbacks=[RichProgressCallback] if TRL_USE_RICH else None,
        )

    trainer.train()

    with save_context:
        trainer.save_model(training_args.output_dir)

    if local_rank == 0:
        hmkdir_rst = hmkdir(args.save_hdfs_path)
        hcopy_rst = hcopy(training_args.output_dir, args.save_hdfs_path)
        print("hmkdir: ", hmkdir_rst)
        print("hcopy: ", hcopy_rst)
