# ==========================================
# Name: Mihai Sergiu Varzare
# Module: Advanced Statistical Programming (ACCA7022)
# Assignment: Alien Colony Resource Management Simulation
# Task: Data Manipulation using Loops Only
# Date: February 2026
# ==========================================

# ==========================================
# INITIAL SETUP
# ==========================================

set.seed(123)  # Set seed for reproducibility
cat("==========================================\n")
cat("ALIEN COLONY RESOURCE MANAGEMENT SIMULATION\n")
cat("==========================================\n\n")

# ==========================================
# TASK 1A – GENERATE PRODUCTION DATA
# Using Nested Loops Only (Optimized with Pre-allocation)
# ==========================================

cat("TASK 1A: Generating Production Data\n")
cat("------------------------------------------\n")

# Calculate total rows: 30 sols × 6 stations × 4 teams
total_rows <- 30 * 6 * 4

# Pre-allocate dataframe for efficiency (avoids repeated rbind)
production_data <- data.frame(
  Sol = integer(total_rows),
  Station = integer(total_rows),
  Team = integer(total_rows),
  Output = numeric(total_rows),
  stringsAsFactors = FALSE
)

# Simulation parameters
BaseOutput <- 50
row_index <- 1

# Nested loops to populate pre-allocated dataframe
for (sol in 1:30) {
  for (station in 1:6) {
    for (team in 1:4) {
      
      # Generate random noise between -5 and +5
      RandomNoise <- sample(-5:5, 1)
      
      # Calculate output using given formula
      OutputValue <- BaseOutput + (station * 3) + (team * 2) + RandomNoise
      
      # Assign values to pre-allocated row
      production_data$Sol[row_index] <- sol
      production_data$Station[row_index] <- station
      production_data$Team[row_index] <- team
      production_data$Output[row_index] <- OutputValue
      
      row_index <- row_index + 1
    }
  }
}

# Display results
cat("First 10 rows of production_data:\n")
print(head(production_data, 10))
cat("\nTotal rows generated:", nrow(production_data), "(Expected: 720)\n\n")

# ==========================================
# TASK 1B – TOTAL PRODUCTION PER STATION
# Using Manual Summation with Loops
# ==========================================

cat("TASK 1B: Calculating Total Production per Station\n")
cat("------------------------------------------\n")

# Pre-allocate station_totals
station_totals <- data.frame(
  Station = 1:6,
  TotalOutput = numeric(6),
  stringsAsFactors = FALSE
)

# Calculate totals for each station
for (station in 1:6) {
  station_sum <- 0
  
  # Sum all outputs for this station
  for (i in 1:nrow(production_data)) {
    if (production_data$Station[i] == station) {
      station_sum <- station_sum + production_data$Output[i]
    }
  }
  
  station_totals$TotalOutput[station] <- station_sum
}

# Display results
cat("Total Production per Station:\n")
print(station_totals)
cat("\n")

# ==========================================
# TASK 1C – DETECT PRODUCTION ANOMALIES
# Optimized: Single pass through data per station-sol
# ==========================================

cat("TASK 1C: Detecting Production Anomalies\n")
cat("------------------------------------------\n")

# Pre-allocate anomalies dataframe
anomalies <- data.frame(
  Sol = integer(total_rows),
  Station = integer(total_rows),
  Team = integer(total_rows),
  Output = numeric(total_rows),
  Anomaly = logical(total_rows),
  stringsAsFactors = FALSE
)

anomaly_index <- 1

# Detect anomalies in optimized single pass
for (sol in 1:30) {
  for (station in 1:6) {
    
    # Collect all outputs for this sol and station
    team_outputs <- numeric(4)
    team_counter <- 0
    
    for (i in 1:nrow(production_data)) {
      if (production_data$Sol[i] == sol && production_data$Station[i] == station) {
        team_counter <- team_counter + 1
        team_outputs[team_counter] <- production_data$Output[i]
      }
    }
    
    # Calculate daily average (sum of all teams divided by 4)
    daily_sum <- 0
    for (t in 1:4) {
      daily_sum <- daily_sum + team_outputs[t]
    }
    daily_average <- daily_sum / 4
    
    # Check each team for anomaly (handle potential zero average)
    for (t in 1:4) {
      current_output <- team_outputs[t]
      
      # Calculate deviation percentage safely
      if (daily_average > 0) {
        deviation_pct <- abs(current_output - daily_average) / daily_average
        anomaly_flag <- deviation_pct > 0.10  # TRUE if >10% deviation
      } else {
        # If average is zero, any positive output is >10% deviation
        anomaly_flag <- current_output > 0
      }
      
      # Store in pre-allocated anomalies dataframe
      anomalies$Sol[anomaly_index] <- sol
      anomalies$Station[anomaly_index] <- station
      anomalies$Team[anomaly_index] <- t
      anomalies$Output[anomaly_index] <- current_output
      anomalies$Anomaly[anomaly_index] <- anomaly_flag
      
      anomaly_index <- anomaly_index + 1
    }
  }
}

# Display results
cat("First 10 anomalies detected:\n")
anomalies_detected <- anomalies[anomalies$Anomaly == TRUE, ]
if (nrow(anomalies_detected) > 0) {
  print(head(anomalies_detected, 10))
} else {
  cat("No anomalies detected.\n")
}
cat("\nTotal anomalies detected:", sum(anomalies$Anomaly), 
    "out of", nrow(anomalies), "records\n")
cat("Percentage of anomalies:", 
    round(sum(anomalies$Anomaly) / nrow(anomalies) * 100, 2), "%\n\n")

# ==========================================
# TASK 1D – IDENTIFY PEAK PRODUCTIVITY DAYS
# Maximum Daily Output per Station
# ==========================================

cat("TASK 1D: Identifying Peak Productivity Days\n")
cat("------------------------------------------\n")

# Pre-allocate peak_days
peak_days <- data.frame(
  Station = 1:6,
  Sol = integer(6),
  TotalOutput = numeric(6),
  stringsAsFactors = FALSE
)

for (station in 1:6) {
  max_output <- -Inf  # Initialize with smallest possible value
  peak_sol <- 0
  
  # Check each sol for this station
  for (sol in 1:30) {
    daily_sum <- 0
    
    # Sum all team outputs for this station and sol
    for (i in 1:nrow(production_data)) {
      if (production_data$Station[i] == station && production_data$Sol[i] == sol) {
        daily_sum <- daily_sum + production_data$Output[i]
      }
    }
    
    # Update maximum if current daily sum is larger
    if (daily_sum > max_output) {
      max_output <- daily_sum
      peak_sol <- sol
    }
  }
  
  peak_days$Sol[station] <- peak_sol
  peak_days$TotalOutput[station] <- max_output
}

# Display results
cat("Peak Productivity Days:\n")
print(peak_days)
cat("\n")

# ==========================================
# TASK 1E – CALCULATE EFFICIENCY SCORE
# Output / (Station + Team)
# ==========================================

cat("TASK 1E: Calculating Efficiency Scores\n")
cat("------------------------------------------\n")

# Add EfficiencyScore column to production_data
production_data$EfficiencyScore <- numeric(total_rows)

for (i in 1:nrow(production_data)) {
  # Calculate efficiency score (ensure no division by zero)
  denominator <- production_data$Station[i] + production_data$Team[i]
  if (denominator > 0) {
    production_data$EfficiencyScore[i] <- production_data$Output[i] / denominator
  } else {
    production_data$EfficiencyScore[i] <- NA  # Should never happen with our data
  }
}

# Display results
cat("First 10 rows with Efficiency Score:\n")
print(head(production_data[, c("Sol", "Station", "Team", "Output", "EfficiencyScore")], 10))
cat("\n")

# ==========================================
# ADDITIONAL INSIGHTS (Optional - for deeper analysis)
# ==========================================

cat("==========================================\n")
cat("ADDITIONAL INSIGHTS\n")
cat("==========================================\n")

# 1. Station with highest total production
highest_station <- 1
for (s in 2:6) {
  if (station_totals$TotalOutput[s] > station_totals$TotalOutput[highest_station]) {
    highest_station <- s
  }
}
cat("Station with highest total production: Station", highest_station, 
    "(", station_totals$TotalOutput[highest_station], "units)\n")

# 2. Most productive team overall (across all stations and sols)
team_totals <- numeric(4)
for (i in 1:nrow(production_data)) {
  team_totals[production_data$Team[i]] <- team_totals[production_data$Team[i]] + 
    production_data$Output[i]
}

best_team <- 1
for (t in 2:4) {
  if (team_totals[t] > team_totals[best_team]) {
    best_team <- t
  }
}
cat("Most productive team overall: Team", best_team, 
    "(", team_totals[best_team], "units)\n")

# 3. Station with most anomalies
station_anomaly_count <- numeric(6)
for (i in 1:nrow(anomalies)) {
  if (anomalies$Anomaly[i]) {
    station_anomaly_count[anomalies$Station[i]] <- 
      station_anomaly_count[anomalies$Station[i]] + 1
  }
}

most_anomalies <- 1
for (s in 2:6) {
  if (station_anomaly_count[s] > station_anomaly_count[most_anomalies]) {
    most_anomalies <- s
  }
}
cat("Station with most anomalies: Station", most_anomalies, 
    "(", station_anomaly_count[most_anomalies], "anomalies)\n")

# 4. Sol with highest overall production
sol_totals <- numeric(30)
for (i in 1:nrow(production_data)) {
  sol_totals[production_data$Sol[i]] <- sol_totals[production_data$Sol[i]] + 
    production_data$Output[i]
}

best_sol <- 1
for (s in 2:30) {
  if (sol_totals[s] > sol_totals[best_sol]) {
    best_sol <- s
  }
}
cat("Most productive sol overall: Sol", best_sol, 
    "(", sol_totals[best_sol], "units)\n\n")

# ==========================================
# VALIDATION SUMMARY
# ==========================================

cat("==========================================\n")
cat("VALIDATION SUMMARY\n")
cat("==========================================\n")
cat("Task 1A: Production data generated -", nrow(production_data), "rows ✓\n")
cat("Task 1B: Station totals calculated -", nrow(station_totals), "stations ✓\n")
cat("Task 1C: Anomalies detected -", sum(anomalies$Anomaly), "anomalies ✓\n")
cat("Task 1D: Peak days identified -", nrow(peak_days), "stations ✓\n")
cat("Task 1E: Efficiency scores added -", 
    ifelse("EfficiencyScore" %in% names(production_data), "Yes ✓", "No ✗"), "\n")
cat("==========================================\n")
cat("Program completed successfully.\n")