"""Example: Using the Reports service to generate PDFs."""

from sed_sh import SedSH
import json

# Initialize client
client = SedSH()

# Example 1: Create a simple report template
print("=== Example 1: Create report template ===")

html_template = """
<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; padding: 40px; }
        h1 { color: #333; }
        .info { background: #f0f0f0; padding: 20px; border-radius: 5px; }
    </style>
</head>
<body>
    <h1>Invoice #{{invoiceNumber}}</h1>
    <div class="info">
        <p><strong>Customer:</strong> {{customerName}}</p>
        <p><strong>Email:</strong> {{customerEmail}}</p>
        <p><strong>Date:</strong> {{date}}</p>
    </div>
    <h2>Items</h2>
    <table style="width: 100%; border-collapse: collapse;">
        <thead>
            <tr style="background: #333; color: white;">
                <th style="padding: 10px; text-align: left;">Item</th>
                <th style="padding: 10px; text-align: right;">Price</th>
            </tr>
        </thead>
        <tbody>
            {{#each items}}
            <tr style="border-bottom: 1px solid #ddd;">
                <td style="padding: 10px;">{{this.name}}</td>
                <td style="padding: 10px; text-align: right;">${{this.price}}</td>
            </tr>
            {{/each}}
        </tbody>
    </table>
    <h3 style="text-align: right;">Total: ${{total}}</h3>
</body>
</html>
"""

template = client.reports.create_template(
    name="Invoice Template",
    html=html_template,
    expiry_hours=24
)
print(f"Template ID: {template['templateId']}")
print(f"Template name: {template['name']}")
print(f"Generation endpoint: {template['endpoint']}")
print(f"Expires at: {template['expiresAt']}")
print()

# Example 2: Generate a PDF from the template
print("=== Example 2: Generate PDF ===")

invoice_data = {
    "invoiceNumber": "INV-2024-001",
    "customerName": "John Doe",
    "customerEmail": "john@example.com",
    "date": "2024-03-17",
    "items": [
        {"name": "Web Development", "price": "1500.00"},
        {"name": "SEO Optimization", "price": "500.00"},
        {"name": "Hosting (1 year)", "price": "120.00"}
    ],
    "total": "2120.00"
}

pdf = client.reports.generate_pdf(
    template_id=template['templateId'],
    data=invoice_data
)
print(f"Generation ID: {pdf['generationId']}")
print(f"PDF size: {pdf['sizeBytes']} bytes")
print(f"Compute time: {pdf['computeTimeSeconds']:.2f} seconds")
print(f"Download URL: {pdf['downloadUrl']}")
print(f"URL expires at: {pdf['expiresAt']}")
print()

# Example 3: List all templates
print("=== Example 3: List templates ===")
templates = client.reports.list_templates()
print(f"Total templates: {len(templates['templates'])}")
for tpl in templates['templates']:
    print(f"  - {tpl['name']} ({tpl['templateId']})")
    print(f"    Endpoint: {tpl['endpoint']}")
print()

# Example 4: Get template with HTML
print("=== Example 4: Get template details ===")
template_details = client.reports.get_template(template['templateId'])
print(f"Template: {template_details['name']}")
print(f"Size: {template_details['sizeBytes']} bytes")
print(f"HTML preview: {template_details['html'][:100]}...")
print()

# Example 5: List recent generations
print("=== Example 5: List generations ===")
generations = client.reports.list_generations()
print(f"Recent generations: {len(generations['generations'])}")
for gen in generations['generations'][:3]:  # Show first 3
    print(f"  - {gen['generationId']}")
    print(f"    Template: {gen['templateId']}")
    print(f"    Size: {gen['sizeBytes']} bytes")
    print(f"    Compute: {gen['computeTimeSeconds']} seconds")
    if gen['downloadUrl']:
        print(f"    Download: {gen['downloadUrl'][:50]}...")
print()

# Example 6: Advanced template with conditional content
print("=== Example 6: Advanced template with conditionals ===")

advanced_template = """
<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: Arial; padding: 40px; }
        .premium { background: gold; padding: 10px; }
        .standard { background: silver; padding: 10px; }
    </style>
</head>
<body>
    <h1>Order Confirmation</h1>
    <p>Hello {{name}}!</p>

    {{#if isPremium}}
    <div class="premium">
        <strong>Premium Customer</strong> - Thank you for your loyalty!
    </div>
    {{else}}
    <div class="standard">
        Standard shipping
    </div>
    {{/if}}

    <h2>Order Items</h2>
    <ul>
    {{#each items}}
        <li>{{this.name}} - ${{this.price}}</li>
    {{/each}}
    </ul>
</body>
</html>
"""

advanced_tpl = client.reports.create_template(
    name="Order Confirmation",
    html=advanced_template
)

# Generate with premium customer
premium_pdf = client.reports.generate_pdf(
    template_id=advanced_tpl['templateId'],
    data={
        "name": "Alice Premium",
        "isPremium": True,
        "items": [
            {"name": "Widget Pro", "price": "99.99"},
            {"name": "Gadget Max", "price": "149.99"}
        ]
    }
)
print(f"Premium PDF: {premium_pdf['downloadUrl'][:50]}...")

# Generate with standard customer
standard_pdf = client.reports.generate_pdf(
    template_id=advanced_tpl['templateId'],
    data={
        "name": "Bob Standard",
        "isPremium": False,
        "items": [
            {"name": "Widget Basic", "price": "49.99"}
        ]
    }
)
print(f"Standard PDF: {standard_pdf['downloadUrl'][:50]}...")
print()

# Example 7: Practical use case - automated reporting
print("=== Example 7: Automated reporting workflow ===")
print("""
# Common workflow for automated invoice generation:

1. Create template once:
   template = client.reports.create_template(name="Invoice", html=template_html)

2. Store template_id in your database:
   db.settings.update({"invoice_template_id": template['templateId']})

3. Generate PDFs on demand:
   for order in pending_orders:
       pdf = client.reports.generate_pdf(
           template_id=invoice_template_id,
           data={
               "invoiceNumber": order.id,
               "customerName": order.customer.name,
               "items": order.items,
               "total": order.total
           }
       )
       # Send PDF URL to customer via email
       send_email(order.customer.email, pdf['downloadUrl'])
""")
print()

# Clean up - delete templates
print("=== Cleanup ===")
client.reports.delete_template(template['templateId'])
print(f"Deleted template: {template['templateId']}")
client.reports.delete_template(advanced_tpl['templateId'])
print(f"Deleted template: {advanced_tpl['templateId']}")
