from __future__ import annotations

import re
import time
from typing import Any


def safe_name(value: str, max_len: int = 63) -> str:
    """把用户输入清洗成云资源名称可用的安全字符串。"""
    cleaned = re.sub(r"[^A-Za-z0-9_.-]+", "-", value.strip())
    cleaned = cleaned.strip(".-_") or "wawacloud"
    return cleaned[:max_len]


def safe_optional_name(value: str, max_len: int = 63) -> str:
    """清洗可选资源名前缀，空值保持为空。"""
    cleaned = re.sub(r"[^A-Za-z0-9_.-]+", "-", value.strip())
    cleaned = cleaned.strip(".-_")
    return cleaned[:max_len]


def decode_process_output_line(raw: Any) -> str:
    """兼容 UTF-8、GB18030、CP936 解码子进程输出行。"""
    if isinstance(raw, str):
        return raw.rstrip()
    data = bytes(raw or b"")
    if not data:
        return ""
    for encoding in ("utf-8-sig", "utf-8", "gb18030", "cp936"):
        try:
            return data.decode(encoding).rstrip()
        except UnicodeDecodeError:
            continue
    return data.decode("utf-8", errors="replace").rstrip()


def prefix_with_suffix(prefix: str, suffix: str) -> str:
    """给资源名追加后缀，前缀为空时只返回后缀。"""
    return f"{prefix}-{suffix}" if prefix else suffix


def timestamp_name(prefix: str, plan: Any) -> str:
    """按地区 key 和当前时间生成资源名，避免多次创建时重名。"""
    stamp = time.strftime("%m%d%H%M%S", time.localtime())
    plan_key = str(getattr(plan, "key", plan))
    if prefix:
        return safe_name(f"{prefix}-{plan_key}-{stamp}")
    return safe_name(f"{plan_key}-{stamp}")
