#!/usr/bin/env python3
"""
Create an Apache deployment zip for My Daneshyar.

The package includes Laravel source, vendor if present, built frontend assets,
and public files. It excludes node_modules, git data, logs, caches, local
archives, and .env by default.
"""

from __future__ import annotations

import argparse
import os
import time
import zipfile
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
BUILD_DIR = ROOT / "build"


EXCLUDED_DIRS = {
    ".git",
    ".idea",
    ".vscode",
    "node_modules",
    "build",
    "storage/logs",
    "storage/framework/cache",
    "storage/framework/sessions",
    "storage/framework/views",
}

EXCLUDED_FILES = {
    ".env",
    ".DS_Store",
}


def should_exclude(path: Path, include_env: bool) -> bool:
    relative = path.relative_to(ROOT).as_posix()
    name = path.name

    if include_env and relative == ".env":
        return False

    if name in EXCLUDED_FILES:
        return True

    for excluded in EXCLUDED_DIRS:
        if relative == excluded or relative.startswith(excluded + "/"):
            return True

    if relative.endswith(".zip"):
        return True

    return False


def main() -> int:
    parser = argparse.ArgumentParser(description="Package Daneshyar for Apache deployment.")
    parser.add_argument("--include-env", action="store_true", help="Include .env in the package. Not recommended.")
    parser.add_argument("--name", default="", help="Custom output zip filename.")
    args = parser.parse_args()

    BUILD_DIR.mkdir(exist_ok=True)
    timestamp = time.strftime("%Y%m%d-%H%M%S")
    output_name = args.name or f"daneshyar-apache-{timestamp}.zip"
    output_path = BUILD_DIR / output_name

    required = [
        ROOT / "public" / "index.php",
        ROOT / "public" / "build" / "manifest.json",
        ROOT / "artisan",
        ROOT / "composer.json",
    ]
    missing = [path for path in required if not path.exists()]
    if missing:
        print("ERROR: Project is not ready for packaging.")
        for path in missing:
            print(f"Missing: {path}")
        print("Run the Laravel scaffold and build first, then package again.")
        return 1

    with zipfile.ZipFile(output_path, "w", compression=zipfile.ZIP_DEFLATED) as archive:
        for path in ROOT.rglob("*"):
            if path == output_path or should_exclude(path, args.include_env):
                continue
            if path.is_dir():
                continue
            archive.write(path, path.relative_to(ROOT).as_posix())

    print(f"Package created: {output_path}")
    print("Remember: Apache DocumentRoot must point to the package's public/ directory.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
