############################################################
# ACCA7022 - Task 1A: Generate Production Data (loops only)
# Purpose: Build production_data with Sol, Station, Team, Output
############################################################

set.seed(123)

# Constants from the specification
BaseOutput <- 50
sols <- 30
stations <- 6
teams <- 4

# Total number of rows = 30 * 6 * 4 = 720
n_rows <- sols * stations * teams

# Pre-allocate vectors (still loop-based; avoids growing objects repeatedly)
Sol <- integer(n_rows)
Station <- integer(n_rows)
Team <- integer(n_rows)
Output <- integer(n_rows)

# Populate vectors using nested loops: Sol -> Station -> Team
row_i <- 1
for (s in 1:sols) {
  for (st in 1:stations) {
    for (t in 1:teams) {
      
      # RandomNoise: integer between -5 and +5 (inclusive)
      RandomNoise <- sample(-5:5, size = 1)
      
      # Output formula from the brief
      Output[row_i] <- BaseOutput + (st * 3) + (t * 2) + RandomNoise
      
      # Store identifiers
      Sol[row_i] <- s
      Station[row_i] <- st
      Team[row_i] <- t
      
      row_i <- row_i + 1
    }
  }
}

# Build dataframe in the required column order
production_data <- data.frame(
  Sol = Sol,
  Station = Station,
  Team = Team,
  Output = Output
)

# Display first 10 rows (requirement)
print(head(production_data, 10))

# Sanity checks (optional but useful)
print(nrow(production_data))     # should be 720
print(names(production_data))    # should be Sol Station Team Output

# ----------------------------------------------------------
# Section B: Total Production per Station (loops only)
# station_totals columns: Station, TotalOutput
# ----------------------------------------------------------

stations <- 6  # keep consistent with Section A (or reuse the same variable)

# Accumulator vector for totals per station
totals_by_station <- integer(stations)

# Loop through every row and add its Output to the correct station bucket
for (i in 1:nrow(production_data)) {
  st <- production_data$Station[i]
  totals_by_station[st] <- totals_by_station[st] + production_data$Output[i]
}

# Build the required dataframe
station_totals <- data.frame(
  Station = 1:stations,
  TotalOutput = totals_by_station
)

# Display station_totals (requirement)
print(station_totals)

# ----------------------------------------------------------
# Section C: Detect Production Anomalies (loops only)
# ----------------------------------------------------------

sols <- 30
stations <- 6
teams <- 4  # daily average is total / 4 teams

# 1) Compute daily totals per (Sol, Station)
daily_total <- matrix(0, nrow = sols, ncol = stations)

for (i in 1:nrow(production_data)) {
  s <- production_data$Sol[i]
  st <- production_data$Station[i]
  daily_total[s, st] <- daily_total[s, st] + production_data$Output[i]
}

# 2) Daily average per (Sol, Station) = total / 4 teams
daily_avg <- matrix(0, nrow = sols, ncol = stations)
for (s in 1:sols) {
  for (st in 1:stations) {
    daily_avg[s, st] <- daily_total[s, st] / teams
  }
}

# 3) Mark anomalies for each row
Anomaly <- logical(nrow(production_data))

for (i in 1:nrow(production_data)) {
  s <- production_data$Sol[i]
  st <- production_data$Station[i]
  out <- production_data$Output[i]
  
  avg <- daily_avg[s, st]
  Anomaly[i] <- (abs(out - avg) > (0.10 * avg))
}

# 4) Create anomalies dataframe (required columns)
anomalies <- data.frame(
  Sol = production_data$Sol,
  Station = production_data$Station,
  Team = production_data$Team,
  Output = production_data$Output,
  Anomaly = Anomaly
)

# Display first 10 anomalies detected (Anomaly == TRUE)
# (Built with loops to keep style consistent)
det_Sol <- integer(0)
det_Station <- integer(0)
det_Team <- integer(0)
det_Output <- integer(0)
det_Anomaly <- logical(0)

count <- 0
for (i in 1:nrow(anomalies)) {
  if (anomalies$Anomaly[i]) {
    det_Sol <- c(det_Sol, anomalies$Sol[i])
    det_Station <- c(det_Station, anomalies$Station[i])
    det_Team <- c(det_Team, anomalies$Team[i])
    det_Output <- c(det_Output, anomalies$Output[i])
    det_Anomaly <- c(det_Anomaly, TRUE)
    
    count <- count + 1
    if (count == 10) {
      break
    }
  }
}

anomalies_detected_first10 <- data.frame(
  Sol = det_Sol,
  Station = det_Station,
  Team = det_Team,
  Output = det_Output,
  Anomaly = det_Anomaly
)

print(anomalies_detected_first10)


# ----------------------------------------------------------
# Section D: Identify Peak Productivity Days (loops only)
# ----------------------------------------------------------

sols <- 30
stations <- 6

peak_days <- data.frame(
  Station = 1:stations,
  Sol = integer(stations),
  TotalOutput = integer(stations)
)

# For each station, find the sol with the maximum daily total output
for (st in 1:stations) {
  
  max_total <- -Inf
  max_sol <- 1
  
  for (s in 1:sols) {
    
    # Sum across all teams for this (sol, station)
    day_total <- 0
    
    for (i in 1:nrow(production_data)) {
      if (production_data$Sol[i] == s && production_data$Station[i] == st) {
        day_total <- day_total + production_data$Output[i]
      }
    }
    
    # Update maximum tracker
    if (day_total > max_total) {
      max_total <- day_total
      max_sol <- s
    }
  }
  
  peak_days$Sol[st] <- max_sol
  peak_days$TotalOutput[st] <- max_total
}

# Display peak_days (requirement)
print(peak_days)


# ----------------------------------------------------------
# Section E: Calculate Efficiency Score (loops only)
# EfficiencyScore = Output / (Station + Team)
# ----------------------------------------------------------

EfficiencyScore <- numeric(nrow(production_data))

for (i in 1:nrow(production_data)) {
  EfficiencyScore[i] <- production_data$Output[i] / (production_data$Station[i] + production_data$Team[i])
}

production_data$EfficiencyScore <- EfficiencyScore

# Display first 10 rows of updated dataframe (requirement)
print(head(production_data, 10))

