"""Example: wire the EZ-Input plugin system into a FastAPI application.

Run this file directly to start a demonstration server:

    cd /root/ez-input-plugins/backend
    source .venv/bin/activate
    python fastapi_integration.py

Then visit http://127.0.0.1:8900/plugin/health
"""

from __future__ import annotations

import sys
from pathlib import Path

# Make the plugin system importable when running from this directory.
sys.path.insert(0, str(Path(__file__).parent))

import os

from dotenv import load_dotenv
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from plugin import Plugin
from registry import PluginRegistry


def _build_payments_config() -> dict:
    """Build the configuration dict consumed by the payments plugin."""
    rate_raw = os.getenv("ERC_RATE", "10")
    try:
        rate = float(rate_raw)
    except (ValueError, TypeError):
        rate = 10.0
    return {
        "stripe_secret_key": os.getenv("STRIPE_SECRET_KEY"),
        "stripe_publishable_key": os.getenv("STRIPE_PUBLISHABLE_KEY"),
        "stripe_webhook_secret": os.getenv("STRIPE_WEBHOOK_SECRET"),
        "airwallex_api_key": os.getenv("AIRWALLEX_API_KEY"),
        "airwallex_client_id": os.getenv("AIRWALLEX_CLIENT_ID"),
        "eth_rpc_url": os.getenv("ETH_RPC_URL"),
        "erc20_contract_address": os.getenv("ERC20_CONTRACT_ADDRESS"),
        "merchant_wallet_address": os.getenv("MERCHANT_WALLET_ADDRESS"),
        "merchant_tron_address": os.getenv("MERCHANT_TRON_ADDRESS"),
        "trongrid_api_key": os.getenv("TRONGRID_API_KEY"),
        "trongrid_base_url": os.getenv("TRONGRID_BASE_URL", "https://api.trongrid.io"),
        "usdt_trc20_contract": os.getenv(
            "USDT_TRC20_CONTRACT", "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
        ),
        "public_host": os.getenv("PUBLIC_HOST", "https://ez-input.com"),
        "erc_rate": rate,
        "ltm_url": os.getenv("LTM_URL"),
    }


def create_app(plugin_dir: Path | str | None = None) -> FastAPI:
    """Create a FastAPI app and load EZ-Input plugins from ``plugin_dir``.

    Args:
        plugin_dir: Directory containing plugin files. Defaults to
            ``/root/ez-input-plugins/backend/plugins``.
    """
    load_dotenv(Path(__file__).parent / ".env")

    app = FastAPI(title="EZ-Input Plugin Demo")

    app.add_middleware(
        CORSMiddleware,
        allow_origins=["https://localhost", "https://localhost:8444", "https://ez-input.com"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    registry = PluginRegistry(plugin_dir)
    registry.set_context(
        {"app_root": str(Path(__file__).parent), "payments_config": _build_payments_config()}
    )
    registry.register_all(app)

    @app.get("/health")
    async def root_health() -> dict:
        return {"status": "ok", "service": "ez-input-plugin-host"}

    @app.get("/plugin/status")
    async def plugin_status() -> dict:
        return registry.health()

    @app.get("/plugins")
    async def list_plugins() -> dict:
        """List loaded plugins and the routes they contributed."""
        route_paths = sorted(
            {route.path for route in app.routes if hasattr(route, "path")}
        )
        return {
            "plugins": [
                {
                    "name": plugin.name,
                    "version": plugin.version,
                    "description": plugin.description,
                }
                for plugin in registry.plugins.values()
            ],
            "routes": route_paths,
        }

    return app


if __name__ == "__main__":
    import uvicorn

    app = create_app()
    uvicorn.run(app, host="0.0.0.0", port=8900)
