export const PLUGIN_GUID = 'asc.{7F4E8F35-5D66-47F8-A5B4-6AB3FAACF565}';
export const PLUGIN_VERSION = '0.1.0';
export const PLUGIN_SCOPE = 'onlyoffice:eln-template-fill';
export const PLUGIN_BIZ_MODULE = 'eln.template';
export const PLUGIN_BIZ_SCENE = 'eln.template.fill';

export interface PluginContext {
  apiBaseUrl: string;
  bizDataId: string;
  bizModule: typeof PLUGIN_BIZ_MODULE;
  bizScene: typeof PLUGIN_BIZ_SCENE;
  canFill: boolean;
  documentId: string;
  pluginVersion: typeof PLUGIN_VERSION;
  scope: typeof PLUGIN_SCOPE;
  ticket: string;
}

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === 'object' && value !== null && !Array.isArray(value);
}

function isNonEmptyString(value: unknown): value is string {
  return typeof value === 'string' && value.trim().length > 0;
}

function isHttpUrl(value: unknown): value is string {
  if (!isNonEmptyString(value)) return false;
  try {
    const parsed = new URL(value);
    return ['http:', 'https:'].includes(parsed.protocol) && !parsed.username && !parsed.password && !parsed.search && !parsed.hash;
  } catch {
    return false;
  }
}

export function parsePluginContext(options: unknown): PluginContext {
  if (!isRecord(options)) throw new Error('插件运行上下文无效');
  if (
    !isHttpUrl(options.apiBaseUrl) ||
    !isNonEmptyString(options.ticket) ||
    options.scope !== PLUGIN_SCOPE ||
    !isNonEmptyString(options.documentId) ||
    !isNonEmptyString(options.bizDataId) ||
    options.bizModule !== PLUGIN_BIZ_MODULE ||
    options.bizScene !== PLUGIN_BIZ_SCENE ||
    options.pluginVersion !== PLUGIN_VERSION ||
    typeof options.canFill !== 'boolean'
  ) {
    throw new Error('插件运行上下文无效');
  }
  return {
    apiBaseUrl: options.apiBaseUrl.replace(/\/+$/u, ''),
    ticket: options.ticket,
    scope: options.scope,
    documentId: options.documentId,
    bizDataId: options.bizDataId,
    bizModule: options.bizModule,
    bizScene: options.bizScene,
    pluginVersion: options.pluginVersion,
    canFill: options.canFill,
  };
}
