import numpy as np
import pandas as pd
import pennylane as qml
from pennylane import numpy as pnp

URL = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv"
level = pd.read_csv(URL)["Passengers"].to_numpy(dtype=float)
# a circuit's output is bounded, so model monthly log-changes (stationary), not the trending level
r = np.diff(np.log(level))
r_scale = np.abs(r[:-24]).max()                       # scale with training data only
z = r / r_scale                                       # now within about [-1, 1]

n_lags = n_qubits = 4                                 # one qubit per lag
X = np.stack([z[i:i + n_lags] for i in range(len(z) - n_lags)])
t = z[n_lags:]                                        # next month's scaled log-change
X_tr, t_tr, X_te, t_te = X[:-24], t[:-24], X[-24:], t[-24:]

dev = qml.device("default.qubit", wires=n_qubits)

@qml.qnode(dev)
def circuit(x, weights):
    qml.AngleEmbedding(np.pi * x, wires=range(n_qubits))          # lag window -> rotation angles
    qml.StronglyEntanglingLayers(weights, wires=range(n_qubits))  # trainable entangling layers
    return qml.expval(qml.PauliZ(0))                              # read out a value in [-1, 1]

def predict(weights, scale, bias, X):
    return pnp.stack([scale * circuit(x, weights) + bias for x in X])

def cost(weights, scale, bias, X, t):
    return pnp.mean((predict(weights, scale, bias, X) - t) ** 2)

rng = np.random.default_rng(0)
shape = qml.StronglyEntanglingLayers.shape(n_layers=2, n_wires=n_qubits)
weights = pnp.array(rng.normal(0, 0.1, shape), requires_grad=True)
scale, bias = pnp.array(1.0, requires_grad=True), pnp.array(0.0, requires_grad=True)

opt = qml.AdamOptimizer(stepsize=0.05)
for step in range(120):                                # hybrid loop: quantum forward, classical update
    batch = rng.choice(len(X_tr), size=16, replace=False)
    Xb, tb = X_tr[batch], t_tr[batch]
    weights, scale, bias = opt.step(lambda w, s, b: cost(w, s, b, Xb, tb), weights, scale, bias)
    if step % 30 == 0:
        print(f"step {step:3d}  train MSE {cost(weights, scale, bias, X_tr, t_tr):.4f}")

prev = level[-25:-1]                                  # last observed month before each target
pred = prev * np.exp(np.array(predict(weights, scale, bias, X_te)) * r_scale)
actual = level[-24:]
print(f"one-step-ahead MAE, last 24 months: {np.mean(np.abs(pred - actual)):.1f} passengers")
print(f"naive (repeat last month) MAE:      {np.mean(np.abs(prev - actual)):.1f} passengers")
