# Set a seed so the random numbers are reproducible for testing
set.seed(123) 

# Task 1A: Generate Production Data

# Pre-allocate the dataframe for efficiency (30 sols * 6 stations * 4 teams = 720 rows)
total_rows <- 30 * 6 * 4
production_data <- data.frame(
  Sol = integer(total_rows),
  Station = integer(total_rows),
  Team = integer(total_rows),
  Output = numeric(total_rows)
)

# Counter to keep track of which row we are writing to
row_index <- 1

# Nested loops to generate every combination of Sol, Station, and Team
for (sol in 1:30) {
  for (station in 1:6) {
    for (team in 1:4) {
      
# Generate random environmental noise between -5 and 5
      random_noise <- sample(-5:5, 1)
      
# Calculate the daily output using the assigned formula
      output_val <- 50 + (station * 3) + (team * 2) + random_noise
      
# Assign the calculated values to the current row in the dataframe
      production_data$Sol[row_index] <- sol
      production_data$Station[row_index] <- station
      production_data$Team[row_index] <- team
      production_data$Output[row_index] <- output_val
      
# Move to the next row
      row_index <- row_index + 1
    }
  }
}

print("Task 1A: First 10 rows of generated data")
print(head(production_data, 10))


# Task 1B: Total Production per Station

# Create a small table to store the results
station_totals <- data.frame(
  Station = 1:6,
  TotalOutput = numeric(6)
)

# Loop through each of the 6 stations
for (s in 1:6) {
  current_station_sum <- 0
  
# Scan every row in the main dataset
  for (i in 1:nrow(production_data)) {
# If the row belongs to the station we are currently checking, add its output
    if (production_data$Station[i] == s) {
      current_station_sum <- current_station_sum + production_data$Output[i]
    }
  }
  
# Save the final sum to the results table
  station_totals$TotalOutput[s] <- current_station_sum
}

print("Task 1B: Station Totals")
print(station_totals)


# Task 1C: Detect Production Anomalies

# Pre-allocate an anomalies dataframe (we trim empty rows later)
anomalies <- data.frame(
  Sol = integer(total_rows),
  Station = integer(total_rows),
  Team = integer(total_rows),
  Output = numeric(total_rows),
  Anomaly = logical(total_rows)
)

anomaly_count <- 0

# Loop through every Sol and Station combination
for (s in 1:30) {
  for (st in 1:6) {
    
# Pass 1: Sum the outputs to find the daily average for this station
    daily_sum <- 0
    team_count <- 0
    
    for (i in 1:nrow(production_data)) {
      if (production_data$Sol[i] == s && production_data$Station[i] == st) {
        daily_sum <- daily_sum + production_data$Output[i]
        team_count <- team_count + 1
      }
    }
    
    daily_average <- daily_sum / team_count
    
# Pass 2: Check each team's output against the daily average
    for (i in 1:nrow(production_data)) {
      if (production_data$Sol[i] == s && production_data$Station[i] == st) {
        
# Calculate the absolute deviation and the 10% threshold
        deviation <- abs(production_data$Output[i] - daily_average)
        threshold <- 0.10 * daily_average
        
# If the deviation is greater than 10%, record it as an anomaly
        if (deviation > threshold) {
          anomaly_count <- anomaly_count + 1
          anomalies$Sol[anomaly_count] <- production_data$Sol[i]
          anomalies$Station[anomaly_count] <- production_data$Station[i]
          anomalies$Team[anomaly_count] <- production_data$Team[i]
          anomalies$Output[anomaly_count] <- production_data$Output[i]
          anomalies$Anomaly[anomaly_count] <- TRUE
        }
      }
    }
  }
}

# Remove the empty rows that weren't used
anomalies <- anomalies[1:anomaly_count, ]

print("Task 1C: First 10 Anomalies")
print(head(anomalies, 10))


# Task 1D: Identify Peak Productivity Days

# Create a table to store the peak day for each station
peak_days <- data.frame(
  Station = 1:6,
  Sol = integer(6),
  TotalOutput = numeric(6)
)

# Loop through each station
for (s in 1:6) {
  
# Start with a negative maximum to ensure the first day always overwrites it
  max_output <- -1
  best_sol <- NA
  
# Check all 30 days for this specific station
  for (d in 1:30) {
    
# Calculate the total output for the current day
    daily_total <- 0
    for (i in 1:nrow(production_data)) {
      if (production_data$Station[i] == s && production_data$Sol[i] == d) {
        daily_total <- daily_total + production_data$Output[i]
      }
    }
    
# If this day's total is the highest we've seen, update our records
    if (daily_total > max_output) {
      max_output <- daily_total
      best_sol <- d
    }
  }
  
# Save the best day to our results table
  peak_days$Sol[s] <- best_sol
  peak_days$TotalOutput[s] <- max_output
}

print("Task 1D: Peak Productivity Days")
print(peak_days)


# Task 1E: Efficiency Score

# Add a new column to the main dataframe
production_data$EfficiencyScore <- numeric(nrow(production_data))

# Loop through every row to calculate the score
for (i in 1:nrow(production_data)) {
  
# Calculate denominator: Station + Team
  denominator <- production_data$Station[i] + production_data$Team[i]
  
# Ensure we don't accidentally divide by zero
  if (denominator > 0) {
    production_data$EfficiencyScore[i] <- production_data$Output[i] / denominator
  } else {
    production_data$EfficiencyScore[i] <- 0
  }
}

print("Task 1E: First 10 rows with Efficiency Score")
print(head(production_data, 10))