"""Fetch Plesk buyUrl/upgradeLicenseUrl via extension context.

Plesk resellers configure buyUrl through pm_Context, which is only
accessible from within the Plesk extension runtime. This module
dynamically creates a PHP script, runs it via
``plesk bin extension --exec``, and parses the JSON output.
"""

import json
import logging
import subprocess
from pathlib import Path
from typing import Optional

from defence360agent.application.determine_hosting_panel import (
    is_plesk_installed,
)

logger = logging.getLogger(__name__)

PLESK_MARKETPLACE_FLAG = Path("/var/imunify360/plesk-ext-marketplace")
PLESK_EXT_SCRIPTS_DIR = Path(
    "/usr/local/psa/admin/plib/modules/imunify360/scripts"
)
_SCRIPT_NAME = "get-upgrade-urls.php"
_SCRIPT_CONTENT = """\
<?php
echo json_encode([
    'buyUrl' => pm_Context::getBuyUrl(),
    'upgradeLicenseUrl' => pm_Context::getUpgradeLicenseUrl(),
]);
"""


def _run_plesk_script() -> Optional[dict]:
    """Create a temporary PHP script, execute it, and return parsed JSON."""
    script_path = PLESK_EXT_SCRIPTS_DIR / _SCRIPT_NAME
    try:
        script_path.write_text(_SCRIPT_CONTENT)
        # The daemon runs with umask 0o007, so write_text creates the file
        # as 0o660 — unreadable by the non-root account Plesk uses to run
        # ``plesk bin extension --exec``. Force world-readable.
        script_path.chmod(0o644)
        result = subprocess.run(
            [
                "plesk",
                "bin",
                "extension",
                "--exec",
                "imunify360",
                _SCRIPT_NAME,
            ],
            capture_output=True,
            timeout=30,
        )
        if result.returncode != 0:
            logger.warning(
                "plesk extension --exec failed (rc=%d): %s",
                result.returncode,
                result.stderr[:500],
            )
            return None
        return json.loads(result.stdout)
    except (OSError, subprocess.TimeoutExpired, json.JSONDecodeError) as exc:
        logger.warning("Failed to fetch Plesk upgrade URLs: %s", exc)
        return None
    finally:
        try:
            script_path.unlink(missing_ok=True)
        except OSError:
            pass


def get_plesk_upgrade_urls() -> dict:
    """Return Plesk buyUrl and upgradeLicenseUrl, or empty strings.

    Only runs when Plesk is installed and the extension was installed
    from the Plesk marketplace.

    Returns:
        dict with keys ``buy_url`` and ``upgrade_license_url``,
        both empty strings when not available.
    """
    empty = {"buy_url": "", "upgrade_license_url": ""}
    if not is_plesk_installed() or not PLESK_MARKETPLACE_FLAG.exists():
        return empty

    data = _run_plesk_script()
    if not data:
        return empty

    return {
        "buy_url": (data.get("buyUrl") or "").strip(),
        "upgrade_license_url": (data.get("upgradeLicenseUrl") or "").strip(),
    }
