"""Project-facing wrapper around the vendor {{ module_title }} runtime.

Exports the main runtime facade ({{ module_class_name }}) and provides a
FastAPI registration helper.
"""

from __future__ import annotations

import importlib.util
import os
import sys
from functools import lru_cache
from pathlib import Path
from types import ModuleType
from typing import Any

from fastapi import APIRouter, FastAPI

_VENDOR_MODULE = "{{ rapidkit_vendor_module }}"
_VENDOR_VERSION = "{{ rapidkit_vendor_version }}"
_VENDOR_RELATIVE_PATH = "{{ python_runtime_relative }}"
_VENDOR_ROOT_ENV = "RAPIDKIT_VENDOR_ROOT"
_CACHE_PREFIX = "rapidkit_vendor_stripe_payment"


def _project_root() -> Path:
    current = Path(__file__).resolve()
    for ancestor in current.parents:
        if (ancestor / "pyproject.toml").exists() or (ancestor / "package.json").exists():
            return ancestor
    return current.parents[5]


def _vendor_root() -> Path:
    override = os.getenv(_VENDOR_ROOT_ENV)
    if override:
        return Path(override).expanduser().resolve()
    return _project_root() / ".rapidkit" / "vendor"


def _vendor_base_dir() -> Path:
    root = _vendor_root()
    module_dir = root / _VENDOR_MODULE
    preferred = module_dir / _VENDOR_VERSION if _VENDOR_VERSION else None
    if preferred and preferred.exists():
        return preferred
    candidates = sorted((p for p in module_dir.glob("*") if p.is_dir()), reverse=True)
    if candidates:
        return candidates[0]
    raise RuntimeError(
        "RapidKit vendor payload for '{module}' not found under {root}. "
        "Re-run `rapidkit modules install {module}`.".format(module=_VENDOR_MODULE, root=root)
    )


def _vendor_file() -> Path:
    if not _VENDOR_RELATIVE_PATH:
        raise RuntimeError("Stripe Payment vendor runtime relative path missing from generator context")
    return _vendor_base_dir() / _VENDOR_RELATIVE_PATH


@lru_cache(maxsize=1)
def _load_vendor_module() -> ModuleType:
    vendor_path = _vendor_file()
    if not vendor_path.exists():
        raise RuntimeError(
            "RapidKit vendor Stripe Payment runtime missing at {path}. "
            "Re-run `rapidkit modules install {module}`.".format(path=vendor_path, module=_VENDOR_MODULE)
        )

    module_name = _CACHE_PREFIX + _VENDOR_MODULE.replace("/", "_")
    spec = importlib.util.spec_from_file_location(module_name, vendor_path)
    if spec is None or spec.loader is None:
        raise RuntimeError(f"Unable to load vendor Stripe Payment runtime from {vendor_path}")

    module = importlib.util.module_from_spec(spec)
    sys.modules.setdefault(module_name, module)
    spec.loader.exec_module(module)
    return module


def _resolve_export(name: str) -> Any:
    module = _load_vendor_module()
    try:
        return getattr(module, name)
    except AttributeError as exc:  # pragma: no cover
        raise RuntimeError(f"Vendor Stripe Payment runtime missing attribute '{name}'") from exc


def _resolve_first(*names: str) -> Any:
    module = _load_vendor_module()
    for name in names:
        if hasattr(module, name):
            return getattr(module, name)
    raise RuntimeError(f"Vendor Stripe Payment runtime missing expected exports: {', '.join(names)}")


def refresh_vendor_module() -> None:
    """Clear import caches (useful after upgrading vendor payloads)."""

    _load_vendor_module.cache_clear()


MODULE_NAME = _resolve_export("MODULE_NAME")
MODULE_TITLE = _resolve_export("MODULE_TITLE")

# Vendor runtime currently exposes *Service symbols; keep a stable project API.
StripePaymentConfig = _resolve_first("StripePaymentConfig", "StripePaymentServiceConfig")
StripePayment = _resolve_first("StripePayment", "StripePaymentService")


def register_fastapi(app: FastAPI) -> APIRouter:
    """Attach the {{ module_title }} router to the given FastAPI app."""

    from .routers.{{ module_name }} import build_router

    router = build_router()
    app.include_router(router)
    return router


__all__ = [
    "MODULE_NAME",
    "MODULE_TITLE",
    "StripePayment",
    "StripePaymentConfig",
    "refresh_vendor_module",
    "register_fastapi",
]
