import os
import zipfile
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import onnx
import torchvision.datasets as datasets
from onnxruntime.training import artifacts

############################################
# Configuration
############################################

DATA_DIR = "./fl_dataset_mnist"
TEMP_DIR = "./temp"
DATASET_TAG = "mnist"

NB_CLIENTS = 3
TRAIN_PER_CLIENT = 800
TEST_PER_CLIENT = 200
SERVER_EVAL = 400

os.makedirs(TEMP_DIR, exist_ok=True)
for i in range(NB_CLIENTS):
    os.makedirs(os.path.join(DATA_DIR, f"client_{i}"), exist_ok=True)
os.makedirs(os.path.join(DATA_DIR, "server"), exist_ok=True)

############################################
# Step 1: Download MNIST and split it across the clients and the server
############################################

train_dataset = datasets.MNIST(root="./mnist_raw", train=True, download=True, transform=None)
test_dataset = datasets.MNIST(root="./mnist_raw", train=False, download=True, transform=None)

rng = np.random.default_rng(42)

x_train_full = (np.stack([np.array(img) for img, _ in train_dataset]).astype(np.float32) / 255.0)[:, None, :, :]
y_train_full = np.array([label for _, label in train_dataset]).astype(np.int64)
x_test_full = (np.stack([np.array(img) for img, _ in test_dataset]).astype(np.float32) / 255.0)[:, None, :, :]
y_test_full = np.array([label for _, label in test_dataset]).astype(np.int64)

# Shuffle so that each client/server split is a random subset of MNIST
perm_train = rng.permutation(len(x_train_full))
x_train_full, y_train_full = x_train_full[perm_train], y_train_full[perm_train]
perm_test = rng.permutation(len(x_test_full))
x_test_full, y_test_full = x_test_full[perm_test], y_test_full[perm_test]

# One train/test set per client
for i in range(NB_CLIENTS):
    client_dir = os.path.join(DATA_DIR, f"client_{i}")

    x_tr = x_train_full[i * TRAIN_PER_CLIENT:(i + 1) * TRAIN_PER_CLIENT]
    y_tr = y_train_full[i * TRAIN_PER_CLIENT:(i + 1) * TRAIN_PER_CLIENT]
    x_te = x_test_full[i * TEST_PER_CLIENT:(i + 1) * TEST_PER_CLIENT]
    y_te = y_test_full[i * TEST_PER_CLIENT:(i + 1) * TEST_PER_CLIENT]

    x_tr.tofile(os.path.join(client_dir, f"client_{i}_train_input_{DATASET_TAG}.bin"))
    y_tr.tofile(os.path.join(client_dir, f"client_{i}_train_target_{DATASET_TAG}.bin"))
    x_te.tofile(os.path.join(client_dir, f"client_{i}_test_input_{DATASET_TAG}.bin"))
    y_te.tofile(os.path.join(client_dir, f"client_{i}_test_target_{DATASET_TAG}.bin"))

    print(f"client_{i}: {x_tr.shape[0]} train samples, {x_te.shape[0]} test samples")

# A separate evaluation set for the server, not seen by any client
needed_test = NB_CLIENTS * TEST_PER_CLIENT
x_eval = x_test_full[needed_test:needed_test + SERVER_EVAL]
y_eval = y_test_full[needed_test:needed_test + SERVER_EVAL]
x_eval.tofile(os.path.join(DATA_DIR, "server", f"server_eval_input_{DATASET_TAG}.bin"))
y_eval.tofile(os.path.join(DATA_DIR, "server", f"server_eval_target_{DATASET_TAG}.bin"))
print(f"server: {x_eval.shape[0]} evaluation samples")


############################################
# Step 2: Define the trainable model
#
# Same architecture as the ORT On-Device Training example, see
# /user/client/example_app/odt/ort/
############################################

class CNNModel(nn.Module):
    def __init__(self):
        super(CNNModel, self).__init__()
        self.conv1 = nn.Conv2d(1, 32, kernel_size=3)
        self.pool1 = nn.MaxPool2d(kernel_size=2)
        self.conv2 = nn.Conv2d(32, 64, kernel_size=3)
        self.pool2 = nn.MaxPool2d(kernel_size=2)
        self.flatten = nn.Flatten()
        self.fc1 = nn.Linear(64 * 5 * 5, 128)
        self.fc2 = nn.Linear(128, 10)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = self.pool1(x)
        x = F.relu(self.conv2(x))
        x = self.pool2(x)
        x = self.flatten(x)
        x = F.relu(self.fc1(x))
        x = F.softmax(self.fc2(x), dim=1)
        return x


model = CNNModel()

############################################
# Step 3: Convert the model to ONNX
############################################

onnx_model_path = os.path.join(TEMP_DIR, "model.onnx")
torch.onnx.export(
    model,
    torch.randn(1, 1, 28, 28),
    onnx_model_path,
    input_names=["input"], output_names=["output"],
    dynamic_axes={"input": {0: "batch"}, "output": {0: "batch"}},
    dynamo=False)

############################################
# Step 4: Generate the ORT training artifacts
############################################

requires_grad = []
onnx_model = onnx.load(onnx_model_path)
for node in reversed(onnx_model.graph.node):
    if node.op_type == "Conv" or node.op_type == "Gemm":
        _, second, third = node.input
        requires_grad.extend([second, third])

frozen_params = [
    param.name
    for param in onnx_model.graph.initializer
    if param.name not in requires_grad
]

artifacts.generate_artifacts(
    onnx_model,
    optimizer=artifacts.OptimType.AdamW,
    loss=artifacts.LossType.CrossEntropyLoss,
    requires_grad=requires_grad,
    frozen_params=frozen_params,
    artifact_directory=TEMP_DIR,
    additional_output_names=["output"])

############################################
# Step 5: Zip the artifacts into a single model file
############################################

MODEL = "artifacts-mnist-fl.zip"
files_to_zip = ["checkpoint", "eval_model.onnx", "optimizer_model.onnx", "training_model.onnx"]
with zipfile.ZipFile(MODEL, "w") as zipf:
    for file in files_to_zip:
        zipf.write(os.path.join(TEMP_DIR, file), arcname=file)

print(f"Wrote {MODEL}")
print(f"Wrote the client and server datasets under {DATA_DIR}")
