import jax
import json
import optax
import model
import jax.numpy as jnp
from flax import nnx
from snapshot import Snapshot
from datetime import datetime
from exp_utils import TreeGenerator, TreeTokenizer
import mlflow
import os


def loss_fn(instance, data, target, start, end, indices):
    """ Cosine similarity loss """
    data = instance.embed_rec(data)     # `embed_rec` must be called before `embed_ema`
    target = instance.embed_ema(target) # to trigger EMA accumulation at the correct time
    predict = instance.reason(data, mask=None, q_len=indices, kv_len=indices)
    return 4 * jnp.nanmean(optax.cosine_distance(predict, target)[:, start:end])


@nnx.jit(static_argnames=['start', 'end'])
def train(instance, optimizer, metrics, data, target, start, end, indices):
    grad_fn = nnx.value_and_grad(loss_fn)
    loss, grads = grad_fn(instance, data, target, start, end, indices)
    metrics.update(loss=loss)
    optimizer.update(instance, grads)


def main(depth: int, init_snap: str = None):
    with open('./configs/reasoner_tree.json', 'r') as file:
        config = json.load(file)

        mlflow.log_params(config['model'])
        mlflow.log_params(config['sst'])
        mlflow.log_params({'Tree Depth': depth, 'Node Width': 2})  # Binary trees

        feature = int(config['model']['Feature'])
        attn_feature = int(config['model']['ATTN Feature'])
        ffn_feature = int(config['model']['FFN Feature'])
        num_head = int(config['model']['Head Count'])
        decoder_count = int(config['model']['Decoder Count'])
        init_scalar = float(config['model']['Init Scalar'])
        max_len = int(config['model']['Max Length'])
        rope_base = float(config['model']['RoPE Base'])

        peak_lr = float(config['sst']['Peak LR'])
        gradient_clipping = float(config['sst']['Grads Clipping'])
        weight_decay = float(config['sst']['Weight Decay'])
        total_steps = int(config['sst']['Total Steps'])
        warmup_steps = int(config['sst']['Warmup Steps'])
        accu_steps = int(config['sst']['Accumulation'])
        batch_size = int(config['sst']['Batch Size'])

    context_len = 14 if depth == 2 else 26 if depth == 3 else 52 if depth == 4 else 64

    # Build model instance
    key = jax.random.key(0)
    instance = model.Reasoner(
        feature=feature,
        attn_feature=attn_feature,
        ffn_feature=ffn_feature,
        num_head=num_head,
        decoder_count=decoder_count,
        is_causal=True,
        init_scalar=init_scalar,
        vocab_size=32,
        ema_interval=accu_steps,
        key=key,
        dtype=jnp.bfloat16
    )
    instance.train(
        rope_base=rope_base,
        max_len=max_len
    )

    if init_snap is not None:  # Continue training from constructed initialization
        snap = Snapshot(os.path.dirname(init_snap))
        instance = snap.load(os.path.basename(init_snap), instance)
        instance.reset_embed_ema(accu_steps)  # Reset EMA cache with loaded embedding values

    # Build optimizer & learning rate scheduler
    scheduler = optax.warmup_cosine_decay_schedule(
        init_value=0.0,
        peak_value=peak_lr,
        warmup_steps=warmup_steps,
        decay_steps=total_steps
    )

    optimizer = optax.chain(
        optax.clip_by_global_norm(gradient_clipping),
        optax.adamw(
            learning_rate=scheduler,
            weight_decay=weight_decay,
            b1=0.9,
            b2=0.95,
            eps=1e-6
        )
    )

    if accu_steps == 1:
        optimizer = nnx.Optimizer(instance, optimizer, wrt=nnx.Param)
    else:
        optimizer = nnx.Optimizer(instance, optax.MultiSteps(optimizer, every_k_schedule=accu_steps), wrt=nnx.Param)
    metrics = nnx.MultiMetric(loss=nnx.metrics.Average('loss'))
    snap = Snapshot(path=f'snapshot/tree-search/reasoner/exp_sst_tree-search-d{depth}')

    # Initialize TreeGenerator and TreeTokenizer
    tree_generator = TreeGenerator(
        depth=depth,
        node_width=2,   # Binary trees
        batch_size=batch_size
    )
    tree_tokenizer = TreeTokenizer(context_len=context_len)
    start = 10 if depth == 2 else 22 if depth == 3 else 46 if depth == 4 else 64
    end = 12 if depth == 2 else 25 if depth == 3 else 50 if depth == 4 else 64

    # Train
    for step in range(total_steps):
        # Generate tree data batch
        tree_strings = tree_generator.generate_trees()
        data, target, _, indices = tree_tokenizer.encode(tree_strings)
        train(instance, optimizer, metrics, data, target, start, end, indices)

        if step % 200 == 0:
            train_loss = metrics.compute().get('loss')
            metrics.reset()

            try:
                mlflow.log_metrics({
                    'train loss': float(train_loss),
                    'learning rate': float(scheduler(step)),
                }, step=step)

            except Exception as e:
                print(f'Logging error at step {step}: {e}\n')

            snap.save(f'exp_tree-search_{step}', instance)

    snap.save(f'exp_tree-search_{total_steps}', instance)


if __name__ == '__main__':
    from util import prepare_training_env
    DEPTH = 4
    INIT_SNAP = f'snapshot/tree-search/reasoner/exp_pretrain_tree-search-d{DEPTH}/exp_tree-search_16600'

    mlflow_credential = 'YOUR_MLFLOW_CREDENTIAL'
    mlflow_tracking_uri = 'YOUR_MLFLOW_TRACKING_URI'
    gpu_preallocation_fraction = '.99'
    prepare_training_env(mlflow_tracking_uri, gpu_preallocation_fraction, mlflow_credential)
    mlflow.set_experiment('JEPA-Reasoner')

    with mlflow.start_run(run_name=datetime.now().strftime(f'exp_sst_tree-search-d{DEPTH}_%d/%m/%y-%H:%M')):
        mlflow.set_tag('depth', DEPTH)
        mlflow.set_tag('init_snap', INIT_SNAP)
        main(DEPTH, INIT_SNAP)
