#!/usr/bin/env python3
"""
Apache readiness checker for My Daneshyar.

Run this before uploading/deploying to an Apache server. It checks the Laravel
public entry point, Vite build output, critical writable folders, and common
production safety settings.
"""

from __future__ import annotations

import os
import stat
import sys
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]


CRITICAL_FILES = [
    "artisan",
    "composer.json",
    "package.json",
    "vendor/autoload.php",
    "public/index.php",
    "public/.htaccess",
    "public/manifest.webmanifest",
    "public/service-worker.js",
]

CRITICAL_DIRS = [
    "app",
    "bootstrap",
    "config",
    "database",
    "public",
    "resources",
    "routes",
    "storage",
    "bootstrap/cache",
]


def read_env() -> dict[str, str]:
    env_path = ROOT / ".env"
    values: dict[str, str] = {}
    if not env_path.exists():
        return values

    for line in env_path.read_text(encoding="utf-8", errors="ignore").splitlines():
        stripped = line.strip()
        if not stripped or stripped.startswith("#") or "=" not in stripped:
            continue
        key, value = stripped.split("=", 1)
        values[key.strip()] = value.strip().strip('"').strip("'")
    return values


def is_writable(path: Path) -> bool:
    if not path.exists():
        return False
    return os.access(path, os.W_OK)


def report(status: str, message: str) -> None:
    print(f"[{status}] {message}")


def main() -> int:
    failures = 0
    warnings = 0

    print(f"Checking Apache readiness for: {ROOT}\n")

    for file_path in CRITICAL_FILES:
        if (ROOT / file_path).exists():
            report("OK", f"{file_path} exists")
        else:
            failures += 1
            report("FAIL", f"{file_path} is missing")

    for dir_path in CRITICAL_DIRS:
        if (ROOT / dir_path).is_dir():
            report("OK", f"{dir_path}/ exists")
        else:
            failures += 1
            report("FAIL", f"{dir_path}/ is missing")

    build_manifest = ROOT / "public" / "build" / "manifest.json"
    if build_manifest.exists():
        report("OK", "public/build/manifest.json exists")
    else:
        failures += 1
        report("FAIL", "public/build/manifest.json is missing; run npm run build")

    env_file = ROOT / ".env"
    if env_file.exists():
        report("OK", ".env exists")
        env = read_env()
        app_debug = env.get("APP_DEBUG", "").lower()
        app_env = env.get("APP_ENV", "").lower()

        if app_debug in ("false", "0", "off", "no"):
            report("OK", "APP_DEBUG is disabled")
        else:
            failures += 1
            report("FAIL", "APP_DEBUG should be false in production")

        if app_env == "production":
            report("OK", "APP_ENV is production")
        else:
            warnings += 1
            report("WARN", "APP_ENV is not production")
    else:
        warnings += 1
        report("WARN", ".env is missing; create it on the server from .env.example")

    public_env = ROOT / "public" / ".env"
    if public_env.exists():
        failures += 1
        report("FAIL", "public/.env exists and must be removed immediately")
    else:
        report("OK", "No .env file inside public/")

    for writable_dir in ("storage", "bootstrap/cache"):
        path = ROOT / writable_dir
        if is_writable(path):
            report("OK", f"{writable_dir}/ is writable by current user")
        else:
            warnings += 1
            report("WARN", f"{writable_dir}/ may not be writable by Apache/PHP user")

    node_modules = ROOT / "node_modules"
    if node_modules.exists():
        warnings += 1
        report("WARN", "node_modules exists; do not upload it unless you intentionally need it")
    else:
        report("OK", "node_modules is absent")

    print("\nApache DocumentRoot must point to:")
    print(f"  {ROOT / 'public'}")

    print(f"\nResult: {failures} failure(s), {warnings} warning(s)")
    return 1 if failures else 0


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