"""
Marketing routes - serve the SPA and scraped marketing pages.
"""
import os
from flask import Blueprint, send_from_directory, abort, redirect, url_for, current_app

marketing_bp = Blueprint('marketing', __name__, url_prefix='/')

# SPA build output
SPA_DIR = os.path.join(
    os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
    'static', 'dist'
)

# Scraped marketing assets (for landing pages)
SCRAPED_DIR = '/tmp/command-sovereignty/commandsovereignty.com'


@marketing_bp.route('/login')
def login_redirect():
    """Redirect to SPA login route."""
    return redirect('/auth/login')


@marketing_bp.route('/signup')
def signup_redirect():
    """Redirect to SPA signup route."""
    return redirect('/auth/signup')


@marketing_bp.route('/')
def index():
    """Serve the SPA index.html"""
    return send_from_directory(SPA_DIR, 'index.html')


@marketing_bp.route('/auth/<path:path>')
def auth_spa(path):
    """Serve SPA for auth routes."""
    return send_from_directory(SPA_DIR, 'index.html')


@marketing_bp.route('/app', defaults={'path': ''})
@marketing_bp.route('/app/', defaults={'path': ''})
@marketing_bp.route('/app/<path:path>')
def app_spa(path):
    """Serve SPA for app routes."""
    return send_from_directory(SPA_DIR, 'index.html')


@marketing_bp.route('/admin/<path:path>')
def admin_spa(path):
    """Serve SPA for admin routes."""
    return send_from_directory(SPA_DIR, 'index.html')


@marketing_bp.route('/favicon.svg')
def favicon():
    """Serve favicon"""
    if os.path.exists(os.path.join(SPA_DIR, 'favicon.svg')):
        return send_from_directory(SPA_DIR, 'favicon.svg')
    try:
        return send_from_directory(SCRAPED_DIR, 'favicon.svg')
    except FileNotFoundError:
        abort(404)


@marketing_bp.route('/dist/<path:filename>')
def spa_assets(filename):
    """Serve SPA built assets (CSS, JS, images)."""
    return send_from_directory(SPA_DIR, filename)


@marketing_bp.route('/assets/<path:filename>')
def static_assets(filename):
    """Serve all scraped assets (CSS, JS, images)."""
    return send_from_directory(os.path.join(SCRAPED_DIR, 'assets'), filename)


@marketing_bp.route('/for/<path:page>')
def for_pages(page):
    """Serve scraped sub-pages (single-location.html, multi-location.html, enterprise.html)."""
    try:
        return send_from_directory(os.path.join(SCRAPED_DIR, 'for'), page)
    except FileNotFoundError:
        abort(404)


@marketing_bp.route('/docs/<path:page>')
def docs_pages(page):
    """Serve scraped docs pages."""
    try:
        return send_from_directory(os.path.join(SCRAPED_DIR, 'docs'), page)
    except FileNotFoundError:
        abort(404)