"""
Generates a standalone branded HTML page for each auction listing.
The file is written to AUCTION_PAGES_ROOT/<slug>.html
The domain can be forwarded directly to this file.
"""
import os
from datetime import datetime
from django.conf import settings
from django.template.loader import render_to_string
from django.utils import timezone


def generate_auction_page(listing):
    """
    Render the auction listing template to a static HTML file.
    Called from admin action or CMS save signal.
    """
    output_dir = getattr(settings, 'AUCTION_PAGES_ROOT', '')
    if not output_dir:
        return False

    os.makedirs(output_dir, exist_ok=True)

    filename = f'{listing.slug}.html'
    filepath = os.path.join(output_dir, filename)

    html = render_to_string('public/auction_page.html', {
        'listing': listing,
        'generated_at': timezone.now(),
    })

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

    # Update the listing record
    listing.page_path = f'auction/{filename}'
    listing.page_generated_at = timezone.now()
    listing.save(update_fields=['page_path', 'page_generated_at'])

    return filepath
