#!/usr/bin/env python3
"""
Hugo 博客自动构建和部署脚本

用途：
1. 构建 Hugo 静态站点
2. 复制到 Nginx 目录
3. 设置正确的文件权限

用法：
    python3 build_and_deploy.py [--dry-run]
"""

import os
import sys
import subprocess
import shutil
import logging
from pathlib import Path
from datetime import datetime

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# 路径配置
BLOG_BASE_DIR = Path(__file__).parent.parent
BLOG_PUBLIC_DIR = BLOG_BASE_DIR / "public"
NGINX_BLOG_DIR = Path("/usr/share/nginx/html/blog")

# 检测环境
IS_PRODUCTION = os.getenv("ENVIRONMENT", "development") == "production"


def check_hugo_installed():
    """检查 Hugo 是否安装"""
    try:
        result = subprocess.run(
            ["hugo", "version"],
            capture_output=True,
            text=True,
            timeout=5
        )
        if result.returncode == 0:
            logger.info(f"Hugo installed: {result.stdout.strip()}")
            return True
        else:
            logger.error("Hugo not found")
            return False
    except FileNotFoundError:
        logger.error("Hugo not installed. Please install Hugo: https://gohugo.io/installation/")
        return False
    except Exception as e:
        logger.error(f"Error checking Hugo: {e}")
        return False


def build_hugo_site():
    """构建 Hugo 站点"""
    try:
        logger.info(f"Building Hugo site at {BLOG_BASE_DIR}")

        result = subprocess.run(
            ["hugo", "--minify"],
            cwd=str(BLOG_BASE_DIR),
            capture_output=True,
            text=True,
            timeout=30
        )

        if result.returncode == 0:
            logger.info("Hugo build successful")
            logger.info(result.stdout)
            return True
        else:
            logger.error(f"Hugo build failed: {result.stderr}")
            return False

    except subprocess.TimeoutExpired:
        logger.error("Hugo build timeout (>30s)")
        return False
    except Exception as e:
        logger.error(f"Build error: {e}")
        return False


def deploy_to_nginx(dry_run=False):
    """部署到 Nginx 目录"""
    if not IS_PRODUCTION:
        logger.info("Development environment - skipping Nginx deployment")
        return True

    if not BLOG_PUBLIC_DIR.exists():
        logger.error(f"Public directory not found: {BLOG_PUBLIC_DIR}")
        return False

    try:
        if dry_run:
            logger.info(f"[DRY RUN] Would deploy {BLOG_PUBLIC_DIR} to {NGINX_BLOG_DIR}")
            return True

        # 备份旧的 blog 目录（如果存在）
        if NGINX_BLOG_DIR.exists():
            backup_dir = NGINX_BLOG_DIR.parent / f"blog_backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
            logger.info(f"Backing up old blog to {backup_dir}")
            shutil.move(str(NGINX_BLOG_DIR), str(backup_dir))

        # 复制新构建的文件
        logger.info(f"Copying {BLOG_PUBLIC_DIR} to {NGINX_BLOG_DIR}")
        shutil.copytree(str(BLOG_PUBLIC_DIR), str(NGINX_BLOG_DIR))

        # 设置权限
        logger.info("Setting permissions (755)")
        subprocess.run(
            ["chmod", "-R", "755", str(NGINX_BLOG_DIR)],
            check=True,
            timeout=10
        )

        logger.info(f"Deployed successfully to {NGINX_BLOG_DIR}")
        return True

    except Exception as e:
        logger.error(f"Deployment failed: {e}")
        return False


def main():
    """主函数"""
    dry_run = "--dry-run" in sys.argv

    if dry_run:
        logger.info("Running in DRY RUN mode")

    logger.info("=" * 60)
    logger.info("Hugo Blog Build and Deploy")
    logger.info("=" * 60)
    logger.info(f"Environment: {'production' if IS_PRODUCTION else 'development'}")
    logger.info(f"Blog directory: {BLOG_BASE_DIR}")
    logger.info(f"Public directory: {BLOG_PUBLIC_DIR}")
    logger.info(f"Nginx directory: {NGINX_BLOG_DIR}")
    logger.info("=" * 60)

    # 步骤 1: 检查 Hugo
    if not check_hugo_installed():
        logger.error("Hugo not installed - aborting")
        return 1

    # 步骤 2: 构建站点
    if not build_hugo_site():
        logger.error("Build failed - aborting")
        return 1

    # 步骤 3: 部署到 Nginx
    if not deploy_to_nginx(dry_run):
        logger.error("Deployment failed")
        return 1

    logger.info("=" * 60)
    logger.info("✅ All done!")
    if IS_PRODUCTION:
        logger.info("Visit https://fetchchina.com/blog/")
    else:
        logger.info("Run 'hugo server' to preview locally")
    logger.info("=" * 60)

    return 0


if __name__ == "__main__":
    sys.exit(main())
