# =================================
# Task A - Generate Production Data
# =================================

# creating 4 empty buckets to hold my data
day_vector     <- c()
utility_vector <- c()
team_vector    <- c()
output_vector  <- c()

# looping through all 30 days, 6 utilities and 5 teams
for (day_id in 1:30) {
  for (utility_id in 1:6) {
    for (team_id in 1:5) {
      
      # picking a random number to simulate real world variation
      noise <- sample(-5:5, 1)
      
      # calculating output using the formula from the brief
      output <- 40 + (utility_id * 3) + (team_id * 2) + noise
      
      # dropping each value into its bucket
      day_vector     <- c(day_vector,     day_id)
      utility_vector <- c(utility_vector, utility_id)
      team_vector    <- c(team_vector,    team_id)
      output_vector  <- c(output_vector,  output)
      
    }
  }
}

# putting all 4 buckets together into one table
production_data <- data.frame(
  Day     = day_vector,
  Utility = utility_vector,
  Team    = team_vector,
  Output  = output_vector
)

# quickly checking the first 10 rows look sensible
head(production_data, 10)


# =====================================
# Task B - Total Production per Utility
# =====================================

# two empty buckets for utility numbers and their totals
utility_totals_utility <- c()
utility_totals_output  <- c()

# going through each utility one by one
for (u in 1:6) {
  
  # starting the count at zero for each utility
  total <- 0
  
  # scanning every row in the table
  for (i in 1:nrow(production_data)) {
    
    # if this row is for the current utility add it to the total
    if (production_data$Utility[i] == u) {
      total <- total + production_data$Output[i]
    }
    
  }
  
  # storing the utility and its grand total
  utility_totals_utility <- c(utility_totals_utility, u)
  utility_totals_output  <- c(utility_totals_output,  total)
  
}

# building the summary table from the two buckets
Utility_totals <- data.frame(
  Utility     = utility_totals_utility,
  TotalOutput = utility_totals_output
)

# printing out the final totals
print(Utility_totals)


# ====================================
# Task C - Detect Production Anomalies
# ====================================

# five empty buckets that will later become my anomalies table
anomaly_day     <- c()
anomaly_utility <- c()
anomaly_team    <- c()
anomaly_output  <- c()
anomaly_flag    <- c()

# going through every day and every utility
for (d in 1:30) {
  for (u in 1:6) {
    
    # first getting the total output for this day and utility
    daily_sum <- 0
    
    for (i in 1:nrow(production_data)) {
      if (production_data$Day[i] == d & production_data$Utility[i] == u) {
        daily_sum <- daily_sum + production_data$Output[i]
      }
    }
    
    # dividing by 5 since there are 5 teams to get the daily average
    daily_avg <- daily_sum / 5
    
    # now checking each team to see if they are too far from the average
    for (i in 1:nrow(production_data)) {
      if (production_data$Day[i] == d & production_data$Utility[i] == u) {
        
        # finding out how far this team is from the daily average
        deviation <- abs(production_data$Output[i] - daily_avg)
        
        # anything more than 10% away gets flagged as an anomaly
        if (deviation > 0.10 * daily_avg) {
          flag <- TRUE
        } else {
          flag <- FALSE
        }
        
        # saving everything for this row
        anomaly_day     <- c(anomaly_day,     d)
        anomaly_utility <- c(anomaly_utility, u)
        anomaly_team    <- c(anomaly_team,    production_data$Team[i])
        anomaly_output  <- c(anomaly_output,  production_data$Output[i])
        anomaly_flag    <- c(anomaly_flag,    flag)
        
      }
    }
    
  }
}

# assembling the anomalies table
anomalies <- data.frame(
  Day     = anomaly_day,
  Utility = anomaly_utility,
  Team    = anomaly_team,
  Output  = anomaly_output,
  Anomaly = anomaly_flag
)

# showing the first 10 rows where an anomaly was spotted
head(anomalies[anomalies$Anomaly == TRUE, ], 10)


# ========================================
# Task D - Identify Peak Productivity Days
# ========================================

# three buckets to remember the best day for each utility
peak_utility <- c()
peak_day     <- c()
peak_output  <- c()

# going through each utility to find its best day
for (u in 1:6) {
  
  # resetting the tracker for each utility
  best_day    <- 1
  best_output <- -Inf
  
  # checking every single day
  for (d in 1:30) {
    
    # adding up all team outputs for this day
    day_total <- 0
    
    for (i in 1:nrow(production_data)) {
      if (production_data$Utility[i] == u & production_data$Day[i] == d) {
        day_total <- day_total + production_data$Output[i]
      }
    }
    
    # if this day beats the current best then swap it in
    if (day_total > best_output) {
      best_output <- day_total
      best_day    <- d
    }
    
  }
  
  # locking in the best day for this utility
  peak_utility <- c(peak_utility, u)
  peak_day     <- c(peak_day,     best_day)
  peak_output  <- c(peak_output,  best_output)
  
}

# creating the peak days summary table
peak_days <- data.frame(
  Utility     = peak_utility,
  Day         = peak_day,
  TotalOutput = peak_output
)

# printing the peak days
print(peak_days)


# ===================================
# Task E - Calculate Efficiency Score
# ===================================

# empty bucket to hold all the efficiency scores
efficiency_vector <- c()

# going row by row through the whole table
for (i in 1:nrow(production_data)) {
  
  # dividing output by utility plus team as the formula says
  score <- production_data$Output[i] /
    (production_data$Utility[i] + production_data$Team[i])
  
  # adding the score to the bucket
  efficiency_vector <- c(efficiency_vector, score)
  
}

# sticking the scores on as a new column
production_data$EfficiencyScore <- efficiency_vector

# checking the first 10 rows with the new column
head(production_data, 10)