from __future__ import annotations

from datetime import datetime, timedelta, timezone
from typing import Any

from mode.provision.base import ManageResult, ProvisionContext, ProvisionResult


class GenericBlankProvisionProvider:
    def __init__(self, config: Any):
        self.config = config

    async def provision(self, context: ProvisionContext) -> ProvisionResult:
        instance = context.instance
        upstream_id = f"GEN-{instance.id}"
        upstream_params = dict(context.upstream_params or context.snapshot.get("upstream_params") or {})
        plugin_fields = dict(context.plugin_fields or context.snapshot.get("plugin_fields") or {})
        return ProvisionResult(
            upstream_id=upstream_id,
            hostname=instance.hostname or context.snapshot.get("alias") or f"service-{instance.id}",
            expires_at=datetime.now(timezone.utc) + timedelta(days=_cycle_days(instance.cycle)),
            links=[
                {"label": "实例详情", "url": f"/control/server/{instance.id}"},
            ],
            payload={
                "plugin": "generic_blank",
                "links": [
                    {"label": "实例详情", "url": f"/control/server/{instance.id}"},
                ],
                "snapshot": {
                    "product_id": context.snapshot.get("product_id"),
                    "cycle": context.snapshot.get("cycle"),
                    "quantity": context.snapshot.get("quantity"),
                    "upstream_params": upstream_params,
                    "upstream_param_labels": context.snapshot.get("upstream_param_labels"),
                    "upstream_param_sources": context.snapshot.get("upstream_param_sources"),
                    "product_config_values": context.product_config_values,
                    "plugin_fields": plugin_fields,
                },
            },
            message="通用空白产品已完成插件开通",
        )

    async def manage(
        self,
        action: str,
        context: ProvisionContext,
        payload: dict[str, Any] | None = None,
    ) -> ManageResult:
        if action == "open-panel":
            return ManageResult(
                message="已生成控制台链接",
                payload={"url": f"/control/server/{context.instance.id}"},
            )
        if action == "sync":
            return ManageResult(message="插件状态同步完成", payload={"status": context.instance.status})
        if action == "terminate":
            return ManageResult(message="插件销毁动作已提交", payload={"submitted": True})
        return ManageResult(success=False, message=f"未知管理动作：{action}", retryable=False)

    async def test(self, config: dict[str, Any] | None = None) -> dict[str, Any]:
        return {
            "ok": True,
            "message": "generic_blank 插件加载正常，provider.test() 可调用。",
            "upstream_params_echo": (config or {}).get("upstream_params") if isinstance(config, dict) else {},
            "config_echo": {k: ("***" if "secret" in k or "key" in k else v) for k, v in (config or {}).items()},
        }


def _cycle_days(cycle: str) -> int:
    return {
        "hourly": 1,
        "daily": 1,
        "monthly": 30,
        "quarterly": 90,
        "semi_annually": 180,
        "annually": 365,
        "biennially": 730,
        "triennially": 1095,
        "one_time": 3650,
    }.get(cycle, 30)


def create_provider(config: Any) -> GenericBlankProvisionProvider:
    return GenericBlankProvisionProvider(config)
