"""Deploy Generator for LandingForge."""


class DeployGenerator:
    """Generates Apache vhost configuration and SSL setup script."""

    def __init__(self, config: dict):
        self.config = config
        self.site = config["site"]
        self.deployment = config.get("deployment", {})

    def generate_apache_vhost(self) -> str:
        apache = self.deployment.get("apache", {})
        certbot = self.deployment.get("certbot", {})
        server_name = apache.get("server_name", self.site["domain"])
        server_alias = apache.get("server_alias", f"www.{self.site['domain']}")
        doc_root = apache.get("document_root", f"/var/www/{self.site['domain']}")
        cache_max_age = apache.get("cache_max_age", 2592000)
        admin_email = certbot.get("email", f"admin@{self.site['domain']}")

        vhost = f"""# =====================================================
# LandingForge — Apache Virtual Host Configuration
# Generated by LandingForge
# =====================================================

<VirtualHost *:80>
    ServerName {server_name}
    ServerAlias {server_alias}
    ServerAdmin {admin_email}
    DocumentRoot {doc_root}

    <Directory {doc_root}>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    # PHP-FPM handler
    <FilesMatch \\.php$>
        SetHandler "proxy:unix:/run/php/php-fpm.sock|fcgi://localhost"
    </FilesMatch>

    # Security headers
    Header always set X-Content-Type-Options "nosniff"
    Header always set X-Frame-Options "SAMEORIGIN"
    Header always set X-XSS-Protection "1; mode=block"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"

    # Gzip compression
    <IfModule mod_deflate.c>
        AddOutputFilterByType DEFLATE text/html text/css application/javascript
        AddOutputFilterByType DEFLATE image/svg+xml application/json font/woff2
    </IfModule>

    # Browser caching
    <IfModule mod_expires.c>
        ExpiresActive On
        ExpiresByType text/css           "access plus {cache_max_age} seconds"
        ExpiresByType application/javascript "access plus {cache_max_age} seconds"
        ExpiresByType image/jpeg         "access plus {cache_max_age} seconds"
        ExpiresByType image/png          "access plus {cache_max_age} seconds"
        ExpiresByType image/webp         "access plus {cache_max_age} seconds"
        ExpiresByType font/woff2         "access plus {cache_max_age} seconds"
    </IfModule>

    LogLevel warn
    ErrorLog  ${{APACHE_LOG_DIR}}/{server_name}-error.log
    CustomLog ${{APACHE_LOG_DIR}}/{server_name}-access.log combined
</VirtualHost>
"""
        return vhost

    def generate_ssl_setup(self) -> str:
        apache = self.deployment.get("apache", {})
        certbot = self.deployment.get("certbot", {})
        server_name = apache.get("server_name", self.site["domain"])
        server_alias = apache.get("server_alias", f"www.{self.site['domain']}")
        doc_root = apache.get("document_root", f"/var/www/{self.site['domain']}")
        email = certbot.get("email", f"admin@{self.site['domain']}")
        agree_tos = certbot.get("agree_tos", True)
        redirect_http = certbot.get("redirect_http", True)

        agree_flag = "--agree-tos" if agree_tos else ""
        redirect_flag = "--redirect" if redirect_http else "--no-redirect"

        return f"""#!/usr/bin/env bash
# =====================================================
# LandingForge — SSL Setup Script
# Run as root or with sudo
# =====================================================
set -euo pipefail

DOMAIN="{server_name}"
ALIAS="{server_alias}"
DOCROOT="{doc_root}"
EMAIL="{email}"

echo "==> Checking system..."
if [ "$(id -u)" -ne 0 ]; then
    echo "ERROR: This script must be run as root." >&2
    exit 1
fi

echo "==> Installing required Apache modules..."
a2enmod rewrite headers ssl proxy proxy_fcgi setenvif expires deflate
systemctl reload apache2

echo "==> Checking for certbot..."
if ! command -v certbot &>/dev/null; then
    echo "==> Installing certbot..."
    if command -v apt-get &>/dev/null; then
        apt-get update -qq
        apt-get install -y -qq certbot python3-certbot-apache
    elif command -v dnf &>/dev/null; then
        dnf install -y certbot python3-certbot-apache
    elif command -v yum &>/dev/null; then
        yum install -y certbot python3-certbot-apache
    else
        echo "ERROR: Cannot install certbot automatically. Please install it manually." >&2
        exit 1
    fi
fi

echo "==> Creating document root if it does not exist..."
mkdir -p "$DOCROOT"
chown -R www-data:www-data "$DOCROOT" 2>/dev/null || chown -R apache:apache "$DOCROOT" 2>/dev/null || true

echo "==> Copying virtual host configuration..."
VHOST_FILE="/etc/apache2/sites-available/$DOMAIN.conf"
cp "$(dirname "$0")/apache-vhost.conf" "$VHOST_FILE"
a2ensite "$DOMAIN.conf"
systemctl reload apache2

echo "==> Obtaining SSL certificate via Certbot..."
certbot --apache \\
    -d "$DOMAIN" \\
    -d "$ALIAS" \\
    --email "$EMAIL" \\
    {agree_flag} \\
    --non-interactive \\
    {redirect_flag}

echo "==> Setting up automatic renewal..."
if command -v crontab &>/dev/null; then
    (crontab -l 2>/dev/null; echo "0 3 * * * /usr/bin/certbot renew --quiet --post-hook 'systemctl reload apache2'") | crontab -
fi

echo "==> Reloading Apache..."
systemctl reload apache2

echo ""
echo "✅  SSL setup complete for $DOMAIN"
echo "    Certificate auto-renewal is configured."
echo "    Site should now be accessible at https://$DOMAIN"
"""
