"""
Merchant template preview endpoint — Settings sub-router.

Allows authenticated merchants to preview a site template rendered with their
own branding.  Auth-type templates are blocked from merchant access.
"""

import re

from fastapi import APIRouter, Depends, HTTPException, Path, Query
from sqlalchemy.orm import Session
from typing import Optional

from src.apps.auth.utils.auth import get_current_merchant
from src.core.database import get_db

router = APIRouter()

# Only allow alphanumeric characters and underscores in template keys.
# This prevents path traversal and injection via the key parameter.
_TEMPLATE_KEY_RE = re.compile(r"^[a-zA-Z0-9_]{1,64}$")


@router.get("/{template_key}")
async def preview_template_for_merchant(
    template_key: str = Path(..., min_length=1, max_length=64),
    primary_color: Optional[str] = Query(None, max_length=20),
    secondary_color: Optional[str] = Query(None, max_length=20),
    accent_color: Optional[str] = Query(None, max_length=20),
    current_merchant=Depends(get_current_merchant),
    db: Session = Depends(get_db),
):
    """
    Render a named site template with the current merchant's branding and
    return the rendered HTML, plain-text body, and email subject.

    - Returns 404 if the template does not exist or is inactive.
    - Returns 403 if the template_type is "auth" (platform-only templates).
    """
    if not _TEMPLATE_KEY_RE.match(template_key):
        raise HTTPException(status_code=400, detail="Invalid template key format")

    from src.apps.site_templates import crud as site_template_crud
    from src.apps.site_templates import services as site_template_services
    from src.apps.notifications.services import _get_merchant_branding

    template = site_template_crud.get_template_by_key(db, template_key)

    if not template or not template.is_active:
        raise HTTPException(status_code=404, detail="Template not found or inactive")

    if template.template_type == "auth":
        raise HTTPException(
            status_code=403,
            detail="Auth templates are not accessible to merchants",
        )

    if template.channel != "email":
        raise HTTPException(
            status_code=403,
            detail="Only email templates can be previewed by merchants",
        )

    branding = _get_merchant_branding(db, current_merchant.id)
    # Apply unsaved color overrides from the preview request (live preview)
    if primary_color is not None:
        branding["primary_color"] = primary_color
    if secondary_color is not None:
        branding["text_color"] = secondary_color
    if accent_color is not None:
        branding["accent_color"] = accent_color
    rendered = site_template_services.render_template(template, branding)

    return {
        "html": rendered["html"],
        "text": rendered["text"],
        "subject": template.subject or "",
    }
