export type ParsedOtpAuth = {
  label: string;
  issuer: string | null;
  secret: string;
  algorithm: string;
  digits: number;
  period: number;
};

/**
 * 解析 otpauth://totp/... 或 otpauth://hotp/...（按 TOTP 处理）
 */
export function parseOtpauthUri(uri: string): ParsedOtpAuth | null {
  const s = uri.trim();
  const lower = s.toLowerCase();
  if (!lower.startsWith('otpauth://totp/') && !lower.startsWith('otpauth://hotp/')) {
    return null;
  }
  let url: URL;
  try {
    url = new URL(s);
  } catch {
    return null;
  }
  const secret = url.searchParams.get('secret');
  if (!secret) return null;
  const issuerQP = url.searchParams.get('issuer');
  let pathPart = decodeURIComponent(url.pathname.replace(/^\/+/u, ''));
  if (pathPart.includes(':')) {
    pathPart = pathPart.split(':').pop() ?? pathPart;
  }
  const label = pathPart || '未命名';
  const issuer = issuerQP?.trim() ? issuerQP : null;
  const algorithm = (url.searchParams.get('algorithm') || 'SHA1').toUpperCase();
  const digits = Math.min(
    10,
    Math.max(6, parseInt(url.searchParams.get('digits') || '6', 10) || 6),
  );
  const period = Math.min(
    120,
    Math.max(
      10,
      parseInt(url.searchParams.get('period') || '30', 10) || 30,
    ),
  );
  return {
    label,
    issuer,
    secret,
    algorithm,
    digits,
    period,
  };
}

/** 粘贴文本：可能是 URI 或换行分隔的 URI */
export function parseOtpauthFromText(text: string): ParsedOtpAuth | null {
  const lines = text
    .split(/\r?\n/u)
    .map((l) => l.trim())
    .filter(Boolean);
  for (const line of lines) {
    const p = parseOtpauthUri(line);
    if (p) return p;
  }
  if (text.includes('otpauth://')) {
    const match = text.match(/otpauth:\/\/[^\s]+/iu);
    if (match) return parseOtpauthUri(match[0]!);
  }
  return null;
}
