# ---------------------------------------------------------
# Task 1A: Generate Production Data
# ---------------------------------------------------------

# Set seed so random numbers remain the same
set.seed(123)

# Calculate total number of rows
total_rows <- 30 * 6 * 4

# Create empty vectors to store data
Sol      <- integer(total_rows)
Station  <- integer(total_rows)
Team     <- integer(total_rows)
Output   <- integer(total_rows)

# Set base production value
BaseOutput <- 50

# Row counter
row_index <- 1

# Loop through sols, stations, and teams
for (s in 1:30) {
  for (st in 1:6) {
    for (tm in 1:4) {
      
      # Generate small random variation
      RandomNoise <- sample(-5:5, 1)
      
      # Calculate output
      out <- BaseOutput + (st * 3) + (tm * 2) + RandomNoise
      
      # Store values
      Sol[row_index]     <- s
      Station[row_index] <- st
      Team[row_index]    <- tm
      Output[row_index]  <- out
      
      # Move to next row
      row_index <- row_index + 1
    }
  }
}

# Create final data frame
production_data <- data.frame(
  Sol = Sol,
  Station = Station,
  Team = Team,
  Output = Output
)

# Display first 10 rows
head(production_data, 10)


# ---------------------------------------------------------
# Task 1B: Total Production per Station
# ---------------------------------------------------------

# Check that required columns exist
required_cols <- c("Sol", "Station", "Team", "Output")

for (col in required_cols) {
  if (!col %in% names(production_data)) {
    stop(paste("Missing required column:", col))
  }
}

# Check for missing values in Output column
if (any(is.na(production_data$Output))) {
  stop("Output column contains missing values.")
}

# Create empty dataframe to store station totals
station_totals <- data.frame(
  Station = 1:6,
  TotalOutput = integer(6)
)

# Store total number of rows
n <- nrow(production_data)

# Extract Station and Output columns
station_col <- production_data$Station
output_col  <- production_data$Output

# Loop through each station
for (st in 1:6) {
  
  total <- 0  # Reset total for each station
  
  # Loop through all rows
  for (i in 1:n) {
    if (station_col[i] == st) {
      total <- total + output_col[i]
    }
  }
  
  # Store total production for that station
  station_totals$TotalOutput[st] <- total
}

# Ensure columns are integer type
station_totals$Station <- as.integer(station_totals$Station)
station_totals$TotalOutput <- as.integer(station_totals$TotalOutput)

# Display final result
station_totals



# ---------------------------------------------------------
# Task 1C: Detect Production Anomalies
# ---------------------------------------------------------

# Get total number of rows
n <- nrow(production_data)

# Extract columns from dataset
sol_col <- production_data$Sol
station_col <- production_data$Station
team_col <- production_data$Team
output_col <- production_data$Output

# Create dataframe to store anomaly results
anomalies <- data.frame(
  Sol = sol_col,
  Station = station_col,
  Team = team_col,
  Output = output_col,
  Anomaly = logical(n)   # TRUE or FALSE
)

# Create matrix to store daily averages (30 sols × 6 stations)
daily_avg <- matrix(0, nrow = 30, ncol = 6)

# Calculate daily average for each sol and station
for (s in 1:30) {
  for (st in 1:6) {
    
    total <- 0  # reset total
    
    # Check all rows
    for (i in 1:n) {
      if (sol_col[i] == s && station_col[i] == st) {
        total <- total + output_col[i]
      }
    }
    
    # Divide by 4 teams to get average
    daily_avg[s, st] <- total / 4
  }
}

# Detect anomalies
for (i in 1:n) {
  
  # Get average for that sol and station
  avg <- daily_avg[sol_col[i], station_col[i]]
  
  # Calculate percentage difference
  deviation <- abs(output_col[i] - avg) / avg
  
  # Mark as TRUE if deviation is greater than 10%
  anomalies$Anomaly[i] <- deviation > 0.10
}

# Show first 10 anomaly cases
head(anomalies[anomalies$Anomaly == TRUE, ], 10)




# ---------------------------------------------------------
# Task 1D: Identify Peak Productivity Days
# ---------------------------------------------------------

# Create empty dataframe to store peak results
peak_days <- data.frame(
  Station = 1:6,
  Sol = integer(6),
  TotalOutput = integer(6)
)

# Extract required columns
sol_col <- production_data$Sol
station_col <- production_data$Station
output_col <- production_data$Output

# Get total number of rows
n <- nrow(production_data)

# Loop through each station
for (st in 1:6) {
  
  max_total <- -Inf   # store highest total found
  max_sol <- NA       # store sol of highest total
  
  # Loop through each sol (1 to 30)
  for (s in 1:30) {
    
    total <- 0   # reset total for each sol
    
    # Check all rows and add output
    for (i in 1:n) {
      if (station_col[i] == st && sol_col[i] == s) {
        total <- total + output_col[i]
      }
    }
    
    # If this sol has higher production, update maximum
    if (total > max_total) {
      max_total <- total
      max_sol <- s
    }
  }
  
  # Store peak sol and its total output
  peak_days$Sol[st] <- max_sol
  peak_days$TotalOutput[st] <- max_total
}

# Display final result
peak_days


# ---------------------------------------------------------
# Task 1E: Calculate Efficiency Score
# ---------------------------------------------------------

# Create new column to store efficiency score
production_data$EfficiencyScore <- numeric(nrow(production_data))

# Extract required columns
station_col <- production_data$Station
team_col <- production_data$Team
output_col <- production_data$Output

# Get total number of rows
n <- nrow(production_data)

# Loop through each row to calculate efficiency
for (i in 1:n) {
  
  # Efficiency formula
  production_data$EfficiencyScore[i] <- 
    output_col[i] / (station_col[i] + team_col[i])
}

# Display first 10 rows
head(production_data, 10)