this script doesnt update the ingredients at all, and the packaging updating is not 100% correct. please fix it.

import openpyxl
from openpyxl import load_workbook
import re
from datetime import datetime
import shutil

def find_matching_sheet(workbook, patterns):
  for sheet in workbook.sheetnames:
      for pattern in patterns:
          if re.search(pattern, sheet, re.IGNORECASE):
              return sheet
  return None

def identify_sheet_by_content(workbook, start_row, end_row):
  for sheet_name in workbook.sheetnames:
      sheet = workbook[sheet_name]
      match_count = 0
      for row in range(start_row, end_row + 1):
          if sheet.cell(row=row, column=1).value:
              match_count += 1
      if match_count > (end_row - start_row) * 0.8:  # 80% match threshold
          return sheet_name
  return None

def find_balance_column(sheet, is_fresh_pm):
  for col in sheet.iter_cols(min_row=2, max_row=2):
      header = col[0].value
      if header:
          header = str(header).lower()
          if is_fresh_pm:
              if "closing balance" in header:
                  return col[0].column
          else:
              if "balance" in header:
                  return col[0].column
  return None  # If no matching column found

def process_sheet(sheet, is_fresh_pm):
  balance_column = find_balance_column(sheet, is_fresh_pm)
  if balance_column is None:
      print(f"Warning: Could not find balance column in {'Fresh PM' if is_fresh_pm else 'Ingredients'} sheet.")
      return {}

  data = {}
  for row in sheet.iter_rows(min_row=3, values_only=True):
      material_code = row[0]  # Column A
      balance = row[balance_column - 1]  # balance_column is 1-based

      if material_code and balance is not None:
          try:
              material_code = str(material_code).strip()
              balance = float(balance)
              data[material_code] = balance
          except (ValueError, TypeError):
              print(f"Warning: Non-numeric value '{balance}' found for material code '{material_code}'. Skipping.")

  return data

def update_balance_workbook():
  try:
      current_stock_wb = load_workbook('current_stock.xlsx', data_only=True)
  except FileNotFoundError:
      print("Error: 'current_stock.xlsx' not found in the current directory.")
      return

  # Try to identify sheets by name
  fresh_pm_sheet = find_matching_sheet(current_stock_wb, [r'fresh\s*pm', r'packaging'])
  ingredients_sheet = find_matching_sheet(current_stock_wb, [r'ingredients.*chemicals', r'chemicals.*ingredients'])

  # If name-based identification fails, try content-based identification
  if not fresh_pm_sheet:
      fresh_pm_sheet = identify_sheet_by_content(current_stock_wb, 117, 150)
  if not ingredients_sheet:
      ingredients_sheet = identify_sheet_by_content(current_stock_wb, 1, 50)

  if not fresh_pm_sheet or not ingredients_sheet:
      print("Couldn't find the required sheets in the current_stock workbook.")
      return

  print(f"Identified sheets: Fresh PM - '{fresh_pm_sheet}', Ingredients - '{ingredients_sheet}'")

  fresh_pm_data = process_sheet(current_stock_wb[fresh_pm_sheet], True)
  ingredients_data = process_sheet(current_stock_wb[ingredients_sheet], False)

  print(f"Fresh PM data count: {len(fresh_pm_data)}")
  print(f"Ingredients data count: {len(ingredients_data)}")
  print("Sample data from Fresh PM:", dict(list(fresh_pm_data.items())[:5]))
  print("Sample data from Ingredients:", dict(list(ingredients_data.items())[:5]))

  # Create a copy of the balance file
  timestamp = datetime.now().strftime("%d.%m.%y")
  new_balance_filename = f'balance_updated_{timestamp}.xlsx'
  try:
      shutil.copy2('balance.xlsx', new_balance_filename)
  except FileNotFoundError:
      print("Error: 'balance.xlsx' not found in the current directory.")
      return

  # Open the copied balance file
  new_balance_wb = load_workbook(new_balance_filename)
  balance_sheet = new_balance_wb.active

  # Update column C with new balance
  update_count = 0
  max_row = balance_sheet.max_row

  existing_material_codes = set()
  for row in balance_sheet.iter_rows(min_row=3):
      material_code_cell = row[0]  # Column A
      material_code = material_code_cell.value
      balance_cell = row[2]  # Column C

      if material_code is not None:
          material_code = str(material_code).strip()
          existing_material_codes.add(material_code)

          # Initialize new_balance as None
          new_balance = None

          if material_code in fresh_pm_data:
              new_balance = fresh_pm_data[material_code]

          if material_code in ingredients_data:
              if new_balance is not None:
                  new_balance += ingredients_data[material_code]
              else:
                  new_balance = ingredients_data[material_code]

          if new_balance is not None:
              balance_cell.value = new_balance
              update_count += 1

  # Now add new material codes from fresh_pm_data and ingredients_data that are not in balance sheet
  new_material_codes = set(fresh_pm_data.keys()).union(set(ingredients_data.keys())) - existing_material_codes
  for material_code in new_material_codes:
      new_balance = fresh_pm_data.get(material_code, 0) + ingredients_data.get(material_code, 0)
      # Append new row at the end
      max_row += 1
      balance_sheet.cell(row=max_row, column=1, value=material_code)  # Column A
      balance_sheet.cell(row=max_row, column=2, value="New Item")  # Column B, description placeholder
      balance_sheet.cell(row=max_row, column=3, value=new_balance)  # Column C
      update_count += 1

  new_balance_wb.save(new_balance_filename)
  print(f"Updated balance workbook saved as {new_balance_filename}")
  print(f"Total updates made: {update_count}")

update_balance_workbook()

print("Created/Modified files:")
print(f"balance_updated_{datetime.now().strftime('%d.%m.%y')}.xlsx")