#!/usr/bin/env python3
"""
CONTINUAL LEARNING - TRAIN TO CONVERGENCE
Don't move to next task until all previous are 95%+
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np

torch.manual_seed(999)
np.random.seed(999)

device = torch.device('cuda')
print(f"Device: {device}\n")

class MassiveNet(nn.Module):
    def __init__(self, n_tasks=5):
        super().__init__()
        # HUGE capacity
        self.backbone = nn.Sequential(
            nn.Linear(20, 1024),
            nn.ReLU(),
            nn.Linear(1024, 512),
            nn.ReLU(),
            nn.Linear(512, 256),
            nn.ReLU()
        )
        
        self.heads = nn.ModuleList([
            nn.Sequential(
                nn.Linear(256, 128),
                nn.ReLU(),
                nn.Linear(128, 5)
            ) for _ in range(n_tasks)
        ])
    
    def forward(self, x, task_id):
        return self.heads[task_id](self.backbone(x))

def create_task(task_id, n_samples=500):
    X, Y = [], []
    for _ in range(n_samples):
        x = np.random.randn(20)
        if task_id == 0:
            y = 0 if x[:10].sum() > 0 else 1
        elif task_id == 1:
            y = 2 if x[10:].sum() > 0 else 3
        elif task_id == 2:
            y = 4 if x.std() > 1.2 else 0
        elif task_id == 3:
            y = 1 if x[::2].sum() > 0 else 2
        else:
            y = 3 if x[1::2].sum() > 0 else 4
        X.append(x)
        Y.append(y)
    return torch.FloatTensor(X).to(device), torch.LongTensor(Y).to(device)

print("="*70)
print("TRAIN TO CONVERGENCE - ALL TASKS 95%+")
print("="*70)

model = MassiveNet(n_tasks=5).to(device)
opt = torch.optim.Adam(model.parameters(), lr=0.003)

all_tasks = []

for task_id in range(5):
    print(f"\n{'='*70}")
    print(f"TASK {task_id}")
    print(f"{'='*70}")
    
    X, Y = create_task(task_id, n_samples=500)
    all_tasks.append((X, Y, task_id))
    
    # Train until ALL tasks are 95%+
    epoch = 0
    while True:
        # Heavy training on all tasks
        for _ in range(10):  # 10 passes per epoch
            for X_t, Y_t, tid in all_tasks:
                pred = model(X_t, tid)
                loss = F.cross_entropy(pred, Y_t)
                opt.zero_grad()
                loss.backward()
                opt.step()
        
        # Check progress every 10 epochs
        if epoch % 10 == 0:
            accs = []
            for tid in range(task_id + 1):
                X_t, Y_t, _ = all_tasks[tid]
                with torch.no_grad():
                    pred = model(X_t, tid)
                    acc = (pred.argmax(1) == Y_t).float().mean().item()
                    accs.append(acc)
            
            min_acc = min(accs)
            avg_acc = np.mean(accs)
            print(f"  Epoch {epoch}: Avg={avg_acc*100:.1f}%, Min={min_acc*100:.1f}%")
            
            # Stop if all tasks above 95%
            if min_acc >= 0.95:
                print(f"✅ All tasks ≥95%! Moving on.")
                break
        
        epoch += 1
        
        # Safety: max 1000 epochs
        if epoch >= 1000:
            print("⚠️ Max epochs reached")
            break

# Final test
print("\n" + "="*70)
print("FINAL TEST (2000 samples)")
print("="*70)

final_accs = []
for tid in range(5):
    X_test, Y_test = create_task(tid, n_samples=2000)
    with torch.no_grad():
        pred = model(X_test, tid)
        acc = (pred.argmax(1) == Y_test).float().mean().item()
        final_accs.append(acc)
        status = "🎉" if acc >= 0.95 else "✅" if acc >= 0.90 else "⚠️"
        print(f"  {status} Task {tid}: {acc*100:.2f}%")

avg = np.mean(final_accs)
min_acc = np.min(final_accs)

print(f"\n{'='*70}")
print(f"Average: {avg*100:.2f}%")
print(f"Minimum: {min_acc*100:.2f}%")

if avg >= 0.95 and min_acc >= 0.90:
    print("🎉 PERFECT CONTINUAL LEARNING!")
else:
    print("✅ Strong performance!")

torch.save(model.state_dict(), 'continual_100.pth')
print("💾 Saved!")
