export type JobRole = 'auto' | 'fast' | 'quality';

const ROLE_RE = /ui_profile:\s*(auto|fast|quality)/i;

export function normalizeJobRole(value?: string | null): JobRole {
  const normalized = String(value ?? '').trim().toLowerCase();
  if (normalized === 'fast' || normalized === 'quality') return normalized;
  return 'auto';
}

export function parseUiRole(instruction: string): JobRole {
  return normalizeJobRole(ROLE_RE.exec(instruction)?.[1]);
}

export function resolveJobScheduling(params: {
  role?: string | null;
  /** @deprecated Use role instead */
  profile?: string | null;
  /** @deprecated Ignored — taskClass is derived from role */
  taskClass?: string | null;
  pieceName: string;
  instruction: string;
}): { role: JobRole } {
  // role を優先、なければ deprecated profile からフォールバック
  const explicit = normalizeJobRole(params.role ?? params.profile);
  const role = explicit !== 'auto'
    ? explicit
    : parseUiRole(params.instruction);

  return { role };
}

export function buildSchedulingMetadataBlock(role: JobRole): string {
  return [
    '---',
    `ui_profile: ${role}`,
  ].join('\n');
}
