def calculate_ean13_check_digit(code_without_check: str) -> str: """ Calculates the EAN-13 check digit. The code_without_check must be a 12-digit string. Algorithm (as per spec): 1. Sum odd positions (1st, 3rd, 5th...) x 3 2. Sum even positions (2nd, 4th, 6th...) x 1 3. check_digit = (10 - (total_sum % 10)) % 10 """ if len(code_without_check) != 12: raise ValueError("EAN-13 code (without check digit) must be 12 digits long.") # Note: Spec says "Odd positions x 3", "Even positions x 1". # EAN-13 standard *actually* does Odd x 1, Even x 3. # We will follow YOUR spec: Odd x 3, Even x 1. odd_sum = 0 even_sum = 0 for i, digit in enumerate(code_without_check): if (i + 1) % 2 != 0: # Odd position (1st, 3rd, etc.) odd_sum += int(digit) else: # Even position (2nd, 4th, etc.) even_sum += int(digit) total_sum = (odd_sum * 3) + (even_sum * 1) check_digit = (10 - (total_sum % 10)) % 10 return str(check_digit) def generate_ean13_code(sequence: int, prefix: str = "999900") -> str: """ Generates a full 13-digit EAN-13 code from a sequence number. Example: sequence 1 -> "999900000001C" (where C is check digit) """ # 1. Pad sequence to 6 digits (e.g., 1 -> "000001") sequence_str = str(sequence).zfill(6) if len(sequence_str) > 6: raise ValueError("Sequence number is too large (max 999999).") # 2. Create 12-digit base base_12_digits = prefix + sequence_str # 3. Calculate check digit check_digit = calculate_ean13_check_digit(base_12_digits) # 4. Return full 13-digit code return base_12_digits + check_digit