import os
import sys
from pathlib import Path

PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

os.environ.setdefault("FLASK_CONFIG", "namecheap")

from app import create_app
from app.services.telegram_service import TelegramService


def _status(ok: bool) -> str:
    return "OK" if ok else "WARN"


def _print_check(label: str, ok: bool, detail: str) -> None:
    print(f"[{_status(ok)}] {label}: {detail}")


def run_preflight() -> int:
    app = create_app(os.getenv("FLASK_CONFIG", "namecheap"))
    warnings = 0

    with app.app_context():
        print("KHF SMP Namecheap Shared Hosting Preflight")
        print(f"Config profile: {os.getenv('FLASK_CONFIG', 'namecheap')}")
        print(f"Startup file: passenger_wsgi.py")
        print(f"Entry point: application")
        print()

        required_env = {
            "DATABASE_URL": os.getenv("DATABASE_URL", ""),
            "SECRET_KEY": os.getenv("SECRET_KEY", ""),
        }
        optional_env = {
            "MAIL_HOST": os.getenv("MAIL_HOST", ""),
            "MAIL_USERNAME": os.getenv("MAIL_USERNAME", ""),
            "MAIL_FROM_ADDRESS": os.getenv("MAIL_FROM_ADDRESS", ""),
            "TELEGRAM_BOT_TOKEN": os.getenv("TELEGRAM_BOT_TOKEN", ""),
        }
        for key, value in required_env.items():
            ok = bool(value and "replace-with" not in value and "change-me" not in value)
            _print_check(key, ok, "configured" if ok else "missing or still using a placeholder")
            warnings += 0 if ok else 1
        for key, value in optional_env.items():
            ok = bool(value)
            _print_check(key, ok, "configured" if ok else "not set")
            warnings += 0 if ok else 1

        telegram_username = os.getenv("TELEGRAM_BOT_USERNAME", "").strip()
        if not telegram_username and bool(app.config.get("TELEGRAM_BOT_TOKEN")):
            telegram_username = TelegramService.bot_username() or ""
        username_ok = bool(telegram_username)
        _print_check(
            "TELEGRAM_BOT_USERNAME",
            username_ok,
            telegram_username or "not set",
        )
        warnings += 0 if username_ok else 1

        upload_root = Path(app.config["UPLOAD_ROOT"])
        temp_root = Path(app.config["TEMP_UPLOAD_DIR"])
        log_root = Path(app.config["LOG_DIR"])
        for label, path in (
            ("UPLOAD_ROOT", upload_root),
            ("TEMP_UPLOAD_DIR", temp_root),
            ("LOG_DIR", log_root),
        ):
            is_public = "public_html" in {part.lower() for part in path.parts}
            writable = path.exists() and os.access(path, os.W_OK)
            ok = path.is_absolute() and not is_public and writable
            detail = f"{path} | absolute={path.is_absolute()} | writable={writable} | outside_public_html={not is_public}"
            _print_check(label, ok, detail)
            warnings += 0 if ok else 1

        db_pool_class = os.getenv("DB_POOL_CLASS", "queue").strip().lower()
        db_ok = db_pool_class == "null"
        _print_check("DB_POOL_CLASS", db_ok, f"{db_pool_class or 'queue'}")
        warnings += 0 if db_ok else 1

        max_upload_mb = int(app.config["MAX_UPLOAD_SIZE_MB"])
        upload_ok = max_upload_mb <= 64
        _print_check("MAX_UPLOAD_SIZE_MB", upload_ok, f"{max_upload_mb} MB")
        warnings += 0 if upload_ok else 1

        batch_upload_mb = int(app.config["MAX_UPLOAD_BATCH_SIZE_MB"])
        batch_ok = batch_upload_mb <= 128
        _print_check("MAX_UPLOAD_BATCH_SIZE_MB", batch_ok, f"{batch_upload_mb} MB")
        warnings += 0 if batch_ok else 1

        strict_policy = bool(app.config.get("STRICT_SHARED_UPLOAD_POLICY"))
        _print_check("STRICT_SHARED_UPLOAD_POLICY", strict_policy, str(strict_policy))
        warnings += 0 if strict_policy else 1

        allowed_extensions = [item.lower() for item in app.config.get("ALLOWED_UPLOAD_EXTENSIONS", [])]
        wildcard_ok = not any(item in {"*", "*.*", "all"} for item in allowed_extensions)
        _print_check("ALLOWED_UPLOAD_EXTENSIONS", wildcard_ok, ",".join(allowed_extensions))
        warnings += 0 if wildcard_ok else 1

        blocked_extensions = {item.lower() for item in app.config.get("BLOCKED_UPLOAD_EXTENSIONS", [])}
        dangerous_required = {"exe", "php", "py", "sh", "bat", "ps1"}
        blocked_ok = dangerous_required.issubset(blocked_extensions)
        _print_check(
            "BLOCKED_UPLOAD_EXTENSIONS",
            blocked_ok,
            f"contains dangerous defaults={blocked_ok}",
        )
        warnings += 0 if blocked_ok else 1

        telegram_enabled = bool(app.config.get("TELEGRAM_NOTIFICATIONS_ENABLED"))
        if telegram_enabled:
            telegram_token = os.getenv("TELEGRAM_BOT_TOKEN", "")
            telegram_ok = bool(telegram_token and "replace-with" not in telegram_token)
            _print_check("TELEGRAM_NOTIFICATIONS_ENABLED", telegram_ok, f"enabled={telegram_enabled}")
            warnings += 0 if telegram_ok else 1

        print()
        if warnings:
            print(f"Completed with {warnings} warning(s). Review the Namecheap deployment guide before going live.")
            return 1
        print("Completed successfully. The current configuration is ready for Namecheap shared hosting.")
        return 0


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