#!/usr/bin/env python3
"""Generate 8-card (4x2) business card layout from 6-card template."""
import re, sys

def gen_cards(template_file, is_front=True):
    with open(template_file) as f:
        content = f.read()

    # Remove header text
    content = re.sub(r'<text.*?LOPERBOYS Business Cards - FRONT.*?</text>', '', content)
    content = re.sub(r'<text.*?LOPERBOYS Business Cards - BACK.*?</text>', '', content)

    # Extract one complete card block (clipPath + g group with content)
    # Cards are structured as:
    # <g clip-path="url(#clipN)">
    #   <g transform="translate(X,Y) scale(...)">
    #     ... card content ...
    #   </g>
    # </g>

    card_pattern = r'<g clip-path="url\(#clip\d"\)>\s*<g transform="translate\([^)]*\)" scale\([^)]*\)>(.*?)</g>\s*</g>'
    cards = re.findall(card_pattern, content, re.DOTALL)

    if not cards:
        print(f"No cards found in {template_file}!", file=sys.stderr)
        sys.exit(1)

    card_content = cards[0]  # All cards have same content, just different positions
    print(f"Extracted card template ({len(card_content)} bytes)")

    # Build new SVG
    # 4 rows x 2 cols = 8 cards
    # Card: 252x144 pts, Row spacing: 48 pts gutter, 42 pts top/bottom margin
    positions = [
        ('36.000', '42.000'),
        ('324.000', '42.000'),
        ('36.000', '228.000'),
        ('324.000', '228.000'),
        ('36.000', '414.000'),
        ('324.000', '414.000'),
        ('36.000', '600.000'),
        ('324.000', '600.000'),
    ]

    label = 'FRONT' if is_front else 'BACK'

    svg_parts = []
    svg_parts.append('<?xml version="1.0" encoding="UTF-8"?>')
    svg_parts.append('<svg xmlns="http://www.w3.org/2000/svg" width="8.5in" height="11in" viewBox="0 0 612 792">')
    svg_parts.append('<rect width="612" height="792" fill="white"/>')

    # Clip paths
    for i, (x, y) in enumerate(positions):
        svg_parts.append(f'<clipPath id="clip{i}"><rect x="{x}" y="{y}" width="252" height="144"/></clipPath>')

    # Card blocks
    for i, (x, y) in enumerate(positions):
        block = f'''<g clip-path="url(#clip{i})">
  <g transform="translate({x},{y}) scale(0.29647,0.28800)">
{card_content}  </g>
</g>'''
        svg_parts.append(block)

    svg_parts.append('</svg>')

    return '\n'.join(svg_parts)

# Generate fronts
fronts_8 = gen_cards('bc-fronts.svg', is_front=True)
with open('bc-fronts-8.svg', 'w') as f:
    f.write(fronts_8)
print("Created bc-fronts-8.svg")

# Generate backs (use adjusted version for alignment)
backs_8 = gen_cards('bc-backs-adjusted.svg', is_front=False)
with open('bc-backs-8.svg', 'w') as f:
    f.write(backs_8)
print("Created bc-backs-8.svg")

# Verify
import subprocess
for fname in ['bc-fronts-8.svg', 'bc-backs-8.svg']:
    result = subprocess.run(['grep', '-c', 'clip-path="url(#clip', fname], capture_output=True, text=True)
    print(f"  {fname}: {result.stdout.strip()} cards")
