"""
python examples/scripts/dpo.py \
    --dataset_name=trl-internal-testing/hh-rlhf-helpful-base-trl-style \
    --model_name_or_path=gpt2 \
    --per_device_train_batch_size 4 \
    --learning_rate 1e-3 \
    --gradient_accumulation_steps 1 \
    --logging_steps 10 \
    --eval_steps 500 \
    --output_dir="dpo_anthropic_hh" \
    --warmup_steps 150 \
    --report_to wandb \
    --bf16 \
    --logging_first_step \
    --no_remove_unused_columns

python examples/scripts/dpo.py \
    --dataset_name=trl-internal-testing/hh-rlhf-helpful-base-trl-style \
    --model_name_or_path=gpt2 \
    --per_device_train_batch_size 4 \
    --learning_rate 1e-3 \
    --gradient_accumulation_steps 1 \
    --logging_steps 10 \
    --eval_steps 500 \
    --output_dir="dpo_anthropic_hh" \
    --...im rmsprop \
    --warmup_steps 150 \
    --report_to wandb \
    --bf16 \
    --logging_first_step \
    --no_remove_unused_columns \
    --use_peft \
    --lora_r=16 \
    --lora_alpha=16
"""

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 (
    DPOConfig,
    DPOTrainer,
    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-dpo"):
    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-dpo", 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"})


if __name__ == "__main__":
    parser = TrlParser((CustomArguments, DPOConfig, 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 DPOTrainer...")
    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]
        return row

    ds = ds.map(
        process,
        num_proc=multiprocessing.cpu_count(),
        load_from_cache_file=False,
    )

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

    with init_context:
        trainer = DPOTrainer(
            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)

