import csv
import json
import re
import os

csv_path = '後加工價目forAI_utf8.csv'
html_path = 'workorder-postprocess-sample-remote.html'

# Read CSV
csv_rows = []
with open(csv_path, 'r', encoding='utf-8') as f:
    reader = csv.DictReader(f)
    for row in reader:
        csv_rows.append(row)

# Read HTML
with open(html_path, 'r', encoding='utf-8') as f:
    content = f.read()

# Extract JSON
start_marker = '<script type="application/json" id="erpos-sample-data">'
end_marker = '</script>'
start_idx = content.find(start_marker)
if start_idx == -1:
    print("Error: Start marker not found")
    exit(1)
start_idx += len(start_marker)

end_idx = content.find(end_marker, start_idx)
if end_idx == -1:
    print("Error: End marker not found")
    exit(1)

json_str = content[start_idx:end_idx].strip()
data = json.loads(json_str)

# Find max ID
max_id = 0
# Check if pricing_type_rows is direct or nested
pricing_data = data
if 'pricing' in data and 'pricing_type_rows' in data['pricing']:
    pricing_data = data['pricing']

if 'pricing_type_rows' not in pricing_data:
    print("Error: pricing_type_rows key not found")
    exit(1)

for row in pricing_data['pricing_type_rows']:
    if row.get('id', 0) > max_id:
        max_id = row.get('id', 0)

# Process CSV rows
new_rows = []
current_id = max_id

print(f"Found {len(csv_rows)} rows in CSV.")
print(f"Current max ID: {max_id}")

for row in csv_rows:
    current_id += 1
    
    # Parse Tier
    tier = row['份數']
    min_qty = 0
    max_qty = None
    
    if '以上' in tier:
        try:
            min_qty = int(re.sub(r'\D', '', tier))
        except:
            min_qty = 0
        max_qty = None
    elif '-' in tier:
        parts = tier.split('-')
        try:
            min_qty = int(parts[0])
            max_qty = int(parts[1])
        except:
            pass
    elif '~' in tier:
        parts = tier.split('~')
        try:
            min_qty = int(parts[0])
            max_qty = int(parts[1])
        except:
            pass
    
    # Parse Size Dimensions
    size_str = row['尺寸']
    size_w_min = 0
    size_w_max = 0
    
    if 'A4' in size_str or '210內' in size_str:
         size_w_min = 0
         size_w_max = 210
    elif 'A3' in size_str:
         size_w_min = 211
         size_w_max = 420
    elif '~' in size_str:
        # e.g. 210~470
        parts = size_str.split('~')
        try:
            size_w_min = int(re.sub(r'\D', '', parts[0]))
            size_w_max = int(re.sub(r'\D', '', parts[1]))
        except:
            pass
    elif '以上' in size_str:
         try:
             val = int(re.sub(r'\D', '', size_str))
             size_w_min = val
             size_w_max = 9999
         except:
             pass

    # Construct new row
    new_row = {
        "version_code": "PRC-BASE",
        "type_id": "digital-post",
        "size": row['尺寸'],
        "tier": tier,
        "min_qty": min_qty,
        "max_qty": max_qty,
        "side": row['單位'],
        "vs": row['VS'],
        "vm": row['VM'],
        "vl": row['VL'],
        "two_l": row['2L'],
        "internal": "0",
        "note": row['特殊選項'],
        "color": row['類型'],
        "base_price": row['基本價'],
        "id": current_id
    }
    
    if size_w_max > 0:
        new_row['size_w_min'] = size_w_min
        new_row['size_w_max'] = size_w_max

    new_rows.append(new_row)

print(f"Generated {len(new_rows)} new pricing rows.")

# Append rows
pricing_data['pricing_type_rows'].extend(new_rows)

# Update JSON in content
new_json_str = json.dumps(data, indent=2, ensure_ascii=False)
# Preserve the surrounding script tags and indentation of the script content
new_content = content[:start_idx] + '\n' + new_json_str + '\n  ' + content[end_idx:]

with open(html_path, 'w', encoding='utf-8') as f:
    f.write(new_content)

print("Updated HTML file successfully.")
