# Author: Shaidhul Hasan
# Student ID: 2442113
# Title: ACCA7022 Coursework 1 - Data Manipulation
# Purpose: Alien Colony Resource Management Simulation using R Loops
# Date: February 2026
# --- Task 1A: Generate Production Data ---

# Initialize variables
sols <- 30
stations <- 6
teams <- 4
base_output <- 50

# Create an empty dataframe with pre-defined column types
production_data <- data.frame(Sol = integer(), 
                              Station = integer(), 
                              Team = integer(), 
                              Output = numeric())

# Nested loops to populate the data
# Loop through each Day, then each Station, then each Team
for (s in 1:sols) {
  for (st in 1:stations) {
    for (t in 1:teams) {
      
      # Generate random noise between -5 and 5
      random_noise <- sample(-5:5, 1)
      
      # Calculate Output using the provided formula
      # Output = Base + (Station * 3) + (Team * 2) + Noise
      output_val <- base_output + (st * 3) + (t * 2) + random_noise
      
      # Create a new row
      new_row <- data.frame(Sol = s, Station = st, Team = t, Output = output_val)
      
      # Append to the main dataframe
      production_data <- rbind(production_data, new_row)
    }
  }
}

# Display the first 10 rows
print("Task 1A: First 10 rows of production_data")
print(head(production_data, 10))


# --- Task 1B: Total Production per Station ---

station_totals <- data.frame(Station = integer(), TotalOutput = numeric())

for (st in 1:stations) {
  current_station_sum <- 0
  
  # Loop through production_data to find rows matching the current station
  for (i in 1:nrow(production_data)) {
    if (production_data$Station[i] == st) {
      current_station_sum <- current_station_sum + production_data$Output[i]
    }
  }
  
  # Add the result to station_totals
  station_totals <- rbind(station_totals, data.frame(Station = st, TotalOutput = current_station_sum))
}

print("Task 1B: station_totals")
print(station_totals)


# --- Task 1C: Detect Production Anomalies ---

anomalies <- data.frame(Sol = integer(), Station = integer(), Team = integer(), 
                        Output = numeric(), Anomaly = logical())

# Loop through each Sol and Station to find the average first
for (s in 1:sols) {
  for (st in 1:stations) {
    
    daily_station_sum <- 0
    # Calculate sum of all teams for this specific day and station
    for (i in 1:nrow(production_data)) {
      if (production_data$Sol[i] == s && production_data$Station[i] == st) {
        daily_station_sum <- daily_station_sum + production_data$Output[i]
      }
    }
    
    # Daily average (sum / 4 teams)
    daily_avg <- daily_station_sum / 4
    
    # Check each team's output against the average
    for (i in 1:nrow(production_data)) {
      if (production_data$Sol[i] == s && production_data$Station[i] == st) {
        output_val <- production_data$Output[i]
        
        # Check if deviation is > 10%
        # (Difference between output and average) / average
        deviation <- abs(output_val - daily_avg) / daily_avg
        
        is_anomaly <- FALSE
        if (deviation > 0.10) {
          is_anomaly <- TRUE
          # Add to anomalies dataframe only if TRUE
          new_anomaly_row <- data.frame(Sol = s, Station = st, Team = production_data$Team[i], 
                                        Output = output_val, Anomaly = is_anomaly)
          anomalies <- rbind(anomalies, new_anomaly_row)
        }
      }
    }
  }
}

print("Task 1C: First 10 anomalies detected")
print(head(anomalies, 10))


# --- Task 1D: Identify Peak Productivity Days ---

peak_days <- data.frame(Station = integer(), Sol = integer(), TotalOutput = numeric())

for (st in 1:stations) {
  max_output <- -1
  peak_sol <- 0
  
  for (s in 1:sols) {
    current_day_sum <- 0
    # Sum output for all teams at this station on this day
    for (i in 1:nrow(production_data)) {
      if (production_data$Station[i] == st && production_data$Sol[i] == s) {
        current_day_sum <- current_day_sum + production_data$Output[i]
      }
    }
    
    # Keep track of the maximum sum found
    if (current_day_sum > max_output) {
      max_output <- current_day_sum
      peak_sol <- s
    }
  }
  
  peak_days <- rbind(peak_days, data.frame(Station = st, Sol = peak_sol, TotalOutput = max_output))
}

print("Task 1D: peak_days")
print(peak_days)

# --- Task 1E: Calculate Efficiency Score ---
production_data$EfficiencyScore <- 0  # Use capital 'S'

for (i in 1:nrow(production_data)) {
  st <- production_data$Station[i]
  t  <- production_data$Team[i]
  out <- production_data$Output[i]
  
  # Ensure the column name matches exactly here too
  production_data$EfficiencyScore[i] <- out / (st + t)
}

print("Task 1E: Updated production_data with EfficiencyScore")
print(head(production_data, 10))

