const STANDARD_TEXTURE_UNIFORMS = new Set([
  'uTexture', 'iChannel0', 'iChannel1', 'iChannel2', 'iChannel3',
]);

export function parseShaderParams(shaderSource) {
  const params = [];
  const textureParams = [];
  let effectName = null;
  let currentGroup = 'Parameters';

  for (const line of shaderSource.split('\n')) {
    const nameMatch = line.match(/\/\/\s*@name\s+["']?([^"'\n]+)["']?/i);
    if (nameMatch) {
      effectName = nameMatch[1].trim();
      continue;
    }
    const groupMatch = line.match(/\/\/\s*@group\s+["']?([^"'\n]+)["']?/i);
    if (groupMatch) {
      currentGroup = groupMatch[1].trim();
      continue;
    }
    const textureMatch = line.match(/\/\/\s*@texture\s+(\w+)\s+["']([^"']+)["']/i);
    if (textureMatch) {
      if (!STANDARD_TEXTURE_UNIFORMS.has(textureMatch[1])) {
        textureParams.push({
          uniform: textureMatch[1],
          name: textureMatch[2],
          type: 'texture',
          group: currentGroup,
        });
      }
      continue;
    }
    const paramMatch = line.match(
      /\/\/\s*@param\s+(\w+)\s+["']([^"']+)["']\s+([\d.-]+)\s+([\d.-]+)\s+([\d.-]+)(?:\s+([\d.-]+))?/i,
    );
    if (paramMatch) {
      params.push({
        uniform: paramMatch[1],
        name: paramMatch[2],
        default: Number.parseFloat(paramMatch[3]),
        min: Number.parseFloat(paramMatch[4]),
        max: Number.parseFloat(paramMatch[5]),
        step: paramMatch[6] ? Number.parseFloat(paramMatch[6]) : 0.01,
        group: currentGroup,
      });
    }
  }
  return { effectName, params, textureParams };
}
