export interface ExecutionItem {
  id: string;
  productId: string;
  type: 'bug' | 'feature' | 'task';
  status: 'open' | 'in_progress' | 'done' | 'closed' | 'wont_fix';
  priority: 'critical' | 'high' | 'medium' | 'low';
  title: string;
  description: string;
  labels: string[];
  assignee: string | null;
  reportedBy: string;
  source: 'internal' | 'user_submitted' | 'auto_detected';
  visibility: 'internal' | 'public';
  voteCount: number;
  commentCount: number;
  targetRelease: string | null;
  createdAt: string;
  updatedAt: string;
}

export interface ExecutionCandidate extends ExecutionItem {
  executionScore: number;
  executionReason: string;
}

export interface ExecutionPipeline {
  nextUp: ExecutionCandidate[];
  inFlight: ExecutionCandidate[];
  done: ExecutionCandidate[];
  summary: {
    ready: number;
    inFlight: number;
    done: number;
    totalVotes: number;
  };
}

export interface IssueDraft {
  title: string;
  body: string;
  labels: string[];
}

const PRIORITY_SCORE: Record<ExecutionItem['priority'], number> = {
  critical: 100,
  high: 70,
  medium: 40,
  low: 10,
};

const STATUS_SCORE: Record<ExecutionItem['status'], number> = {
  open: 20,
  in_progress: 80,
  done: 0,
  closed: -20,
  wont_fix: -40,
};

export function scoreExecutionItem(item: ExecutionItem): number {
  return (
    PRIORITY_SCORE[item.priority] +
    STATUS_SCORE[item.status] +
    Math.min(item.voteCount * 3, 60) +
    Math.min(item.commentCount * 2, 20) +
    (item.source === 'user_submitted' ? 10 : 0) +
    (item.visibility === 'public' ? 5 : 0)
  );
}

export function buildExecutionReason(item: ExecutionItem): string {
  const parts = [
    `${item.priority} priority`,
    `${item.voteCount} vote${item.voteCount === 1 ? '' : 's'}`,
  ];
  if (item.commentCount > 0)
    parts.push(`${item.commentCount} comment${item.commentCount === 1 ? '' : 's'}`);
  if (item.source === 'user_submitted') parts.push('customer submitted');
  return parts.join(' · ');
}

function toCandidate(item: ExecutionItem): ExecutionCandidate {
  return {
    ...item,
    executionScore: scoreExecutionItem(item),
    executionReason: buildExecutionReason(item),
  };
}

function sortByExecutionScore(a: ExecutionCandidate, b: ExecutionCandidate): number {
  if (b.executionScore !== a.executionScore) return b.executionScore - a.executionScore;
  return b.updatedAt.localeCompare(a.updatedAt);
}

export function buildExecutionPipeline(items: ExecutionItem[], limit = 5): ExecutionPipeline {
  const candidates = items.map(toCandidate).sort(sortByExecutionScore);
  const nextUp = candidates.filter(item => item.status === 'open').slice(0, limit);
  const inFlight = candidates.filter(item => item.status === 'in_progress').slice(0, limit);
  const done = candidates.filter(item => item.status === 'done').slice(0, limit);

  return {
    nextUp,
    inFlight,
    done,
    summary: {
      ready: items.filter(item => item.status === 'open').length,
      inFlight: items.filter(item => item.status === 'in_progress').length,
      done: items.filter(item => item.status === 'done').length,
      totalVotes: items.reduce((sum, item) => sum + item.voteCount, 0),
    },
  };
}

export function buildIssueDraft(item: ExecutionItem): IssueDraft {
  const labels = Array.from(new Set(['roadmap', item.type, item.priority, ...item.labels]));
  return {
    title: `[${item.type}] ${item.title}`,
    labels,
    body: [
      `## Roadmap request`,
      ``,
      item.description || '_No description provided._',
      ``,
      `## Signal`,
      `- Priority: ${item.priority}`,
      `- Votes: ${item.voteCount}`,
      `- Comments: ${item.commentCount}`,
      `- Source: ${item.source}`,
      `- Reporter: ${item.reportedBy}`,
      ``,
      `## Links`,
      `- Public status: /status/${item.id}`,
      `- Tracker item: /dashboard/items/${item.id}`,
      ``,
      `## Acceptance criteria`,
      `- [ ] Confirm scope and user impact`,
      `- [ ] Implement with tests`,
      `- [ ] Update roadmap status when shipped`,
    ].join('\n'),
  };
}
