# Set seed for reproducibility
set.seed(123)

# Generate Production Data

# Define fixed parameters
total_days    <- 30   # number of days of operation
total_utility <- 6    # number of utility services
total_teams   <- 5    # number of operational teams per utility
base_output   <- 40   # fixed base output value

# Create empty vectors to store each column
day_col     <- c()
utility_col <- c()
team_col    <- c()
output_col  <- c()

# Nested loops: iterate over each day, utility, and team
for (d in 1:total_days) {
  for (u in 1:total_utility) {
    for (t in 1:total_teams) {

      # Calculate random noise: integer between -5 and +5
      random_noise <- sample(-5:5, 1)

      # Calculate output:
      # Output = (UtilityID x TeamID) + BaseOutput + RandomNoise
      output_value <- (u * t) + base_output + random_noise

      # Append each value to its respective column vector
      day_col     <- c(day_col, d)
      utility_col <- c(utility_col, u)
      team_col    <- c(team_col, t)
      output_col  <- c(output_col, output_value)
    }
  }
}

# Combine all column vectors into one data frame
production_data <- data.frame(
  Day     = day_col,
  Utility = utility_col,
  Team    = team_col,
  Output  = output_col
)

# Display the first 10 rows
print(head(production_data, 10))


# Total Production per Utility

# Create empty vectors for the summary data frame
utility_ids   <- c()
total_outputs <- c()

# Loop through each utility and sum all outputs using a loop
for (u in 1:total_utility) {

  running_total <- 0  # reset total for each utility

  # Loop through every row of production_data
  for (i in 1:nrow(production_data)) {

    # Check if this row belongs to the current utility
    if (production_data$Utility[i] == u) {
      running_total <- running_total + production_data$Output[i]
    }
  }

  # Store the utility ID and its total output
  utility_ids   <- c(utility_ids, u)
  total_outputs <- c(total_outputs, running_total)
}

# Build the Utility_totals data frame
Utility_totals <- data.frame(
  Utility     = utility_ids,
  TotalOutput = total_outputs
)

# Display the result
print(Utility_totals)


# Detect Production Anomalies

# Create empty vectors for the anomalies data frame
anom_day     <- c()
anom_utility <- c()
anom_team    <- c()
anom_output  <- c()
anom_flag    <- c()

# Loop through each day and each utility to find anomalies
for (d in 1:total_days) {
  for (u in 1:total_utility) {

    # Step 1: Calculate the daily average output for this utility
    daily_sum   <- 0
    daily_count <- 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]
        daily_count <- daily_count + 1
      }
    }

    # Daily average = sum of all teams / 4 (as specified in the task)
    daily_avg <- daily_sum / 4

    # Step 2: Check each team's output against the daily average
    for (i in 1:nrow(production_data)) {
      if (production_data$Day[i] == d && production_data$Utility[i] == u) {

        team_output <- production_data$Output[i]

        # Calculate deviation percentage from the daily average
        deviation <- abs(team_output - daily_avg) / daily_avg * 100

        # Mark as anomaly if deviation is more than 10%
        if (deviation > 10) {
          is_anomaly <- TRUE
        } else {
          is_anomaly <- FALSE
        }

        # Append row to anomaly vectors
        anom_day     <- c(anom_day, d)
        anom_utility <- c(anom_utility, u)
        anom_team    <- c(anom_team, production_data$Team[i])
        anom_output  <- c(anom_output, team_output)
        anom_flag    <- c(anom_flag, is_anomaly)
      }
    }
  }
}

# Build the anomalies data frame
anomalies <- data.frame(
  Day     = anom_day,
  Utility = anom_utility,
  Team    = anom_team,
  Output  = anom_output,
  Anomaly = anom_flag
)

# Display first 10 anomalies detected (rows where Anomaly = TRUE)
anomaly_rows <- anomalies[anomalies$Anomaly == TRUE, ]
print(head(anomaly_rows, 10))


# Identify Peak Productivity Days

# Create empty vectors for peak_days data frame
peak_utility <- c()
peak_day     <- c()
peak_output  <- c()

# Loop through each utility to find its peak day
for (u in 1:total_utility) {

  best_day    <- 0   # will store the day with highest output
  best_output <- -1  # start with -1 so any real output replaces it

  # Loop through each day
  for (d in 1:total_days) {

    # Calculate total output for this utility on 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]
      }
    }

    # Update best day if this day has a higher total output
    if (day_total > best_output) {
      best_output <- day_total
      best_day    <- d
    }
  }

  # Store the result for this utility
  peak_utility <- c(peak_utility, u)
  peak_day     <- c(peak_day, best_day)
  peak_output  <- c(peak_output, best_output)
}

# Build peak_days data frame
peak_days <- data.frame(
  Utility     = peak_utility,
  Day         = peak_day,
  TotalOutput = peak_output
)

# Display peak_days
print(peak_days)


# Calculate Efficiency Score

# Create empty vector to hold efficiency scores
efficiency_scores <- c()

# Loop through each row and calculate efficiency score
# Formula: EfficiencyScore = (Output / BaseOutput) * 100
for (i in 1:nrow(production_data)) {
  score <- (production_data$Output[i] / base_output) * 100
  efficiency_scores <- c(efficiency_scores, score)
}

# Add EfficiencyScore as a new column to production_data
production_data$EfficiencyScore <- efficiency_scores

print(head(production_data, 10))
