const CSP_META_REGEX = /<meta\s+http-equiv="content-security-policy"\s+content="([^"]+)"\s*\/?>/i;

export function extractCsp(html: string): { csp: string; html: string } {
  const match = html.match(CSP_META_REGEX);
  if (!match) {
    return { csp: '', html };
  }

  return {
    csp: match[1],
    html: html.replace(match[0], ''),
  };
}

export function augmentCsp(baseCsp: string, additions: Record<string, string[]>): string {
  if (!baseCsp) {
    return '';
  }

  const directives = new Map<string, Set<string>>();

  for (const part of baseCsp.split(';')) {
    const trimmed = part.trim();
    if (!trimmed) {
      continue;
    }

    const [directive, ...values] = trimmed.split(/\s+/);
    directives.set(directive, new Set(values));
  }

  for (const [directive, values] of Object.entries(additions)) {
    const existing = directives.get(directive) ?? new Set<string>();
    for (const value of values) {
      existing.add(value);
    }
    directives.set(directive, existing);
  }

  return [...directives.entries()].map(([directive, values]) => `${directive} ${[...values].join(' ')}`).join('; ');
}
