#!/usr/bin/env python3
"""Fix email_service.py f-string error and quotes.py field name mismatch."""

# Fix 1: email_service.py - backslash in f-string
with open('/opt/claudetools/api/services/email_service.py', 'r') as f:
    lines = f.read().split('\n')

# Find and replace the problematic line
fixed_email = False
insert_idx = None
for i, line in enumerate(lines):
    if 'One-Time Costs' in line and 'fff7ed' in line:
        lines[i] = '            {setup_costs_html}'
        fixed_email = True
        print(f'Replaced problematic f-string at line {i+1}')
        break

# Find the 'return f"""' line (after line 100) and insert variable before it
for i, line in enumerate(lines):
    if 'return f"""' in line and i > 100:
        insert_idx = i
        break

if insert_idx is not None:
    var_lines = [
        '    setup_costs_html = ""',
        '    if float(setup_total or 0) > 0:',
        '        setup_costs_html = (',
        '            "<div style=\'background: #fff7ed; border-radius: 8px; padding: 12px 20px; "',
        '            "margin-bottom: 20px;\'><span style=\'color: #9a3412; font-size: 14px;\'>"',
        '            "One-Time Costs: <strong>$" + setup_total + "</strong></span></div>"',
        '        )',
        '',
    ]
    for j, vl in enumerate(var_lines):
        lines.insert(insert_idx + j, vl)
    print(f'Inserted setup_costs_html variable before line {insert_idx+1}')

with open('/opt/claudetools/api/services/email_service.py', 'w') as f:
    f.write('\n'.join(lines))
print('email_service.py saved')

# Fix 2: quotes.py - item.service_name -> item.product_name
with open('/opt/claudetools/api/routers/quotes.py', 'r') as f:
    content = f.read()

if 'item.service_name' in content:
    content = content.replace('item.service_name', 'item.product_name')
    print('Fixed item.service_name -> item.product_name in quotes.py')
else:
    print('item.service_name not found in quotes.py (may already be fixed)')

with open('/opt/claudetools/api/routers/quotes.py', 'w') as f:
    f.write(content)
print('quotes.py saved')

# Verify no syntax errors
import py_compile
try:
    py_compile.compile('/opt/claudetools/api/services/email_service.py', doraise=True)
    print('[OK] email_service.py: syntax OK')
except py_compile.PyCompileError as e:
    print(f'[ERROR] email_service.py SYNTAX ERROR: {e}')

try:
    py_compile.compile('/opt/claudetools/api/routers/quotes.py', doraise=True)
    print('[OK] quotes.py: syntax OK')
except py_compile.PyCompileError as e:
    print(f'[ERROR] quotes.py SYNTAX ERROR: {e}')
