#!/usr/bin/env python3
"""
CONTINUAL LEARNING - PUSH TO 100%
Longer training, better architecture, balanced task training
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np

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

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

class PerfectMultiHead(nn.Module):
    def __init__(self, n_tasks=5):
        super().__init__()
        # Larger, deeper backbone
        self.backbone = nn.Sequential(
            nn.Linear(20, 512),
            nn.BatchNorm1d(512),
            nn.ReLU(),
            nn.Dropout(0.1),
            nn.Linear(512, 256),
            nn.BatchNorm1d(256),
            nn.ReLU(),
            nn.Dropout(0.1),
            nn.Linear(256, 128),
            nn.BatchNorm1d(128),
            nn.ReLU()
        )
        
        # Stronger task heads
        self.heads = nn.ModuleList([
            nn.Sequential(
                nn.Linear(128, 64),
                nn.ReLU(),
                nn.Linear(64, 5)
            ) for _ in range(n_tasks)
        ])
    
    def forward(self, x, task_id):
        features = self.backbone(x)
        return self.heads[task_id](features)

def create_task(task_id, n_samples=300):
    """More samples for better learning"""
    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[5:15].mean() > 0 else 3
        elif task_id == 2:
            y = 4 if x[-10:].std() > 1.0 else 0
        elif task_id == 3:
            y = 1 if x[::2].sum() > 0 else 2
        else:
            y = 3 if np.abs(x).max() > 1.5 else 4
        
        X.append(x)
        Y.append(y)
    
    return torch.FloatTensor(X).to(device), torch.LongTensor(Y).to(device)

print("="*70)
print("CONTINUAL LEARNING - PUSHING TO 100%")
print("="*70)

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

all_tasks = []
task_accuracies = []

# Learn 5 tasks sequentially
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=300)
    all_tasks.append((X, Y, task_id))
    
    # Extended training - 300 epochs
    for epoch in range(300):
        total_loss = 0
        
        # Balanced training on all tasks
        for X_t, Y_t, tid in all_tasks:
            # Mini-batch training
            batch_size = 32
            for i in range(0, len(X_t), batch_size):
                batch_X = X_t[i:i+batch_size]
                batch_Y = Y_t[i:i+batch_size]
                
                pred = model(batch_X, tid)
                loss = F.cross_entropy(pred, batch_Y)
                total_loss += loss
        
        opt.zero_grad()
        total_loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        opt.step()
        
        if epoch % 60 == 0:
            with torch.no_grad():
                pred = model(X, task_id)
                acc = (pred.argmax(1) == Y).float().mean()
                print(f"  Epoch {epoch}: Task {task_id} acc={acc.item()*100:.1f}%")
    
    # Test all tasks
    print(f"\nTesting:")
    task_accs = []
    for tid in range(task_id + 1):
        X_test, Y_test = create_task(tid, n_samples=300)
        with torch.no_grad():
            pred = model(X_test, tid)
            acc = (pred.argmax(1) == Y_test).float().mean().item()
            task_accs.append(acc)
            status = "✅" if acc >= 0.95 else "⚠️" if acc >= 0.90 else "❌"
            print(f"  {status} Task {tid}: {acc*100:.1f}%")
    
    task_accuracies.append(task_accs)

# Extra fine-tuning pass on all tasks together
print("\n" + "="*70)
print("FINAL FINE-TUNING")
print("="*70)

for epoch in range(100):
    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()

# Final test
print("\n" + "="*70)
print("FINAL RESULTS")
print("="*70)

final_accs = []
for tid in range(5):
    X_test, Y_test = create_task(tid, n_samples=500)
    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:.1f}%")

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

print(f"\nAverage: {avg_acc*100:.1f}%")
print(f"Minimum: {min_acc*100:.1f}%")

if avg_acc >= 0.95 and min_acc >= 0.90:
    print("🎉 PERFECT! Continual learning at 95%+!")
elif avg_acc >= 0.90:
    print("✅ EXCELLENT!")
else:
    print("✅ Good progress!")

torch.save(model.state_dict(), 'continual_perfect.pth')
print("💾 Model saved!")
