#!/usr/bin/env python3

import torch
import torch.nn as nn
import torch.optim as optim

# 1. Set seed for clean, reproducible results
torch.manual_seed(42)

# 2. Build the "Overlapping Heights" Dataset
# Height 4.0: 100% Children (0)
# Height 5.0:  80% Children (0) 
#              20% Adults (1) 
# Height 6.0: 100% Adults (1)
X_list, y_list = [], []

for _ in range(100):
    X_list.append([-1.0]); y_list.append(0)  # Pure Child data
    X_list.append([ 1.0]); y_list.append(1)  # Pure Adult data

for _ in range(80):
    X_list.append([ 0.0]); y_list.append(0)  # Ambiguous: 80% Child
for _ in range(20):
    X_list.append([ 0.0]); y_list.append(1)  # Ambiguous: 20% Adult

X = torch.tensor(X_list, dtype=torch.float32)     # input
y = torch.tensor(y_list, dtype=torch.float32)     # label


# 3. Define the Dual-Head RLCD Network Architecture
class RLCDToyModel(nn.Module):
    def __init__(self):
        super().__init__()
# Shared representation backbone
        self.backbone = nn.Sequential(
            nn.Linear(1, 32),
            nn.ReLU(),
            nn.Linear(32, 32),
            nn.ReLU()                )

# Head 1: Output 2 logits for the discrete decision (0 or 1)
        self.decision_head = nn.Linear(32, 2)
        
# Head 2: Output 1 scalar confidence score bounded between 0.0 and 1.0
        self.confidence_head = nn.Linear(32, 1)

    def forward(self, x):
        features = self.backbone(x)
        logits = self.decision_head(features)
        p = torch.sigmoid(self.confidence_head(features)).squeeze(-1)
#                 ->[0,1]                                 last dim not needed
        return logits, p


# 4. Instantiate Model & Optimization Parameters
model = RLCDToyModel()
optimizer = optim.Adam(model.parameters(), lr=0.005)

print("# starting training loop...")

# 5. Training Loop using Policy Gradient (REINFORCE Contextual Bandit)
for epoch in range(1000):
    optimizer.zero_grad()
    
# Forward Pass
    logits, p = model(X)
    
# Decision Head: Sample discrete actions based on output logits
# categorical distribution: finite support
# dist is a PyTorch object: probabilities (is_child,is_adult)
    dist = torch.distributions.Categorical(logits=logits)
    sampled_action = dist.sample()    # draw one according to probabilities
    
# Reinforcement == environmental feedback 
# y_indicator: 1.0 if the random choice was right, 0.0 if wrong
    y_indicator = (sampled_action == y).float()
    
# RLCD reward:  y - (y - p)^2
#   RLCD_reward = y_indicator - torch.square(y_indicator - p)
    RLCD_reward = 2.0*y_indicator - 1.0
    
# Cross-entropy loss of policy, viz of action taken
# unlike dist.sample(), dist.log_prob() propagates gradients back
    log_probs = dist.log_prob(sampled_action)

# RF learning for the the decision head 
# --> treat as an RLCD_reward  --> detach()
# mean() --> batch average
    policy_loss = -(log_probs * RLCD_reward.detach()).mean()
    
# Confidence head loss for supervised learning
# --> enforces calibration constraint across batch
# == (1-RLCD_reward).mean()
    confidence_loss = nn.MSELoss()(p, y_indicator)
    
# Loss combination, backpropagation, weight update step
    total_loss = policy_loss + confidence_loss
    total_loss.backward()
    optimizer.step()

print("# training finished\n")

# 6. Evaluation profile with logits and action policies
print("--- Model Behavior Verification ---")
test_inputs = torch.tensor([[-1.0], [0.0], [1.0]], dtype=torch.float32)

with torch.no_grad():
    logits, p = model(test_inputs)
    # Convert raw logits into explicit policy probabilities (0 to 1)
    policies = torch.softmax(logits, dim=-1)
    preds = torch.argmax(logits, dim=-1)

# Format and view the distribution profiles
labels = ["Child (0)", "Adult (1)"]
for i, height in enumerate([4.0, 5.0, 6.0]):
    print(f"\n[Height Input: {height}]")
    print(f"  Raw Logits:       Child: {logits[i][0]:.2f} | Adult: {logits[i][1]:.2f}")
    print(f"  Decision Policy:  P(Child): {policies[i][0]:.4f} | P(Adult): {policies[i][1]:.4f}")
    print(f"  Sampled Action:   {labels[preds[i]]}")
    print(f"  Confidence Head:  p = {p[i].item():.4f}")
