### Task A: Generating Production Data

# Reproducibility
set.seed(123)

# Constants
base_output <- 50
total_sols <- 30
total_stations <- 6
total_teams <- 4

# Initializing empty vectors
sol_col <- c()
station_col <- c()
team_col <- c()
output_col <- c()

# Triple nested loop
for (s in 1:total_sols) {
  for (st in 1:total_stations) {
    for (t in 1:total_teams) {
      
      # Random noise between -5 and +5
      random_noise <- sample(-5:5, 1)
      
      # Required formula
      daily_val <- base_output + (st * 5) + (t * 3) + random_noise
      
      # Append
      sol_col <- c(sol_col, s)
      station_col <- c(station_col, st)
      team_col <- c(team_col, t)
      output_col <- c(output_col, daily_val)
    }
  }
}

# Building dataframe
production_data <- data.frame(
  Sol = sol_col,
  Station = station_col,
  Team = team_col,
  Output = output_col
)

cat(" Production Data (First 10 Rows) \n")
print(head(production_data, 10))
cat("\n")


### Task B: Total Production per Station

station_ids <- 1:total_stations
total_outputs <- numeric(total_stations)

# Outer loop choosing the station
for (i in 1:total_stations) {
  
  running_total <- 0
  
  # Inner loop scanning the entire dataset
  for (j in 1:nrow(production_data)) {
    if (production_data$Station[j] == station_ids[i]) {
      running_total <- running_total + production_data$Output[j]
    }
  }
  
  total_outputs[i] <- running_total
}

station_totals <- data.frame(
  Station = station_ids,
  TotalOutput = total_outputs
)

cat(" Total Production per Station \n")
print(station_totals)
cat("\n")


# Task C: Detecting Production Anomalies

# Empty dataframe to store results
anomalies <- data.frame(
  Sol = numeric(),
  Station = numeric(),
  Team = numeric(),
  Output = numeric(),
  Anomaly = logical()
)

# Loop through each day and station
for (s in 1:total_sols) {
  for (st in 1:total_stations) {
    
    # calculating station total for this sol
    day_sum <- 0
    for (k in 1:nrow(production_data)) {
      if (production_data$Sol[k] == s &&
          production_data$Station[k] == st) {
        day_sum <- day_sum + production_data$Output[k]
      }
    }
    
    # average across 4 teams
    day_avg <- day_sum / total_teams
    
    # checking deviation
    for (k in 1:nrow(production_data)) {
      if (production_data$Sol[k] == s &&
          production_data$Station[k] == st) {
        
        # manual absolute difference
        val <- production_data$Output[k]
        diff <- val - day_avg
        if (diff < 0) { diff <- -diff }
        
        is_anom <- FALSE
        if (diff > (0.10 * day_avg)) {
          is_anom <- TRUE
        }
        
        anomalies <- rbind(
          anomalies,
          data.frame(Sol=s, Station=st,
                     Team=production_data$Team[k],
                     Output=val,
                     Anomaly=is_anom)
        )
      }
    }
  }
}

cat(" First 10 TRUE anomalies \n")

count <- 0
for (i in 1:nrow(anomalies)) {
  if (anomalies$Anomaly[i] == TRUE && count < 10) {
    print(anomalies[i, ])
    count <- count + 1
  }
}
cat("\n")


# Task D: Identifying Peak Productivity Days

peak_station <- numeric(total_stations)
peak_sol <- numeric(total_stations)
peak_output <- numeric(total_stations)

for (st in 1:total_stations) {
  
  max_val <- -1
  best_day <- 0
  
  for (s in 1:total_sols) {
    
    daily_sum <- 0
    
    for (i in 1:nrow(production_data)) {
      if (production_data$Station[i] == st &&
          production_data$Sol[i] == s) {
        daily_sum <- daily_sum + production_data$Output[i]
      }
    }
    
    if (daily_sum > max_val) {
      max_val <- daily_sum
      best_day <- s
    }
  }
  
  peak_station[st] <- st
  peak_sol[st] <- best_day
  peak_output[st] <- max_val
}

peak_days <- data.frame(
  Station = peak_station,
  Sol = peak_sol,
  TotalOutput = peak_output
)

cat(" Peak Productivity Days \n")
print(peak_days)
cat("\n")


# Task E: Calculating Efficiency Score

efficiency_vec <- numeric(nrow(production_data))

for (i in 1:nrow(production_data)) {
  
  expected <- base_output +
    production_data$Station[i] * 5 +
    production_data$Team[i] * 3
  
  efficiency_vec[i] <- (production_data$Output[i] / expected) * 100
}

# Adding to original dataframe
production_data$EfficiencyScore <- efficiency_vec

cat(" Updated Data with Efficiency Score (First 10) \n")
print(head(production_data, 10))


