// Idea capture pipeline (kb#170): classify -> Todoist task.
//
// Deliberately does NOT create/move anything in Kanboard, Radicale, or
// gitea — kb#170 component 4 ("Adolf предлагает, какие идеи созрели")
// is a human-in-the-loop periodic review, not an automatic conversion.
// This module only tags the idea so that later review has something to
// act on (labels: area-*, urgency-*, and "decompose" when flagged).
//
// Project/label mapping is a deliberate v1 decision, not a guess left
// unstated: Todoist's real projects today (Inbox, One-Off, Family,
// Planning, Pending — confirmed live via todoist_list_projects) don't
// line up with the 5 kb#170 areas except "семья" ~= "Family". Creating
// four new Todoist projects to match Adolf/Welfare/дом/здоровье is a
// structural change to the user's real Todoist account, so it is NOT done
// here without explicit sign-off — see kb#170 report. Instead every idea
// keeps its default project (Inbox, unless the caller passes one) and
// gets an `area-*` label, which is purely additive/reversible (Todoist
// auto-creates labels on first use, and any label can be deleted later
// with zero data loss).
import { classifyIdea } from './classifier.js';
import { todoistCreateTask } from './todoist.js';

const FAMILY_PROJECT_NAME = 'Family';

// urgency label -> Todoist API priority (1=normal..4=urgent, inverse of
// the Todoist UI's p1..p4 — see todoist.js header comment).
const URGENCY_TO_PRIORITY = { high: 4, medium: 2, low: 1 };

export async function todoistCaptureIdea({ text, project_id } = {}, { listProjects = null, createTask = todoistCreateTask } = {}) {
  if (!text || !text.trim()) throw new Error('text is required');

  const classification = await classifyIdea(text.trim());

  const labels = [`area-${classification.area.label}`, `urgency-${classification.urgency.label}`];
  if (classification.decompose.label === 'needs-decomposition') labels.push('decompose');
  if (classification.area.ambiguous) labels.push('area-uncertain');

  // Only auto-route to an existing project when it's an unambiguous, exact
  // match (семья -> Family) — never invent/select a project the classifier
  // merely guessed at, and never override a project_id the caller passed
  // explicitly.
  let resolvedProjectId = project_id;
  if (!resolvedProjectId && classification.area.label === 'семья' && !classification.area.ambiguous && typeof listProjects === 'function') {
    const projects = await listProjects();
    const family = projects.find((p) => p.name === FAMILY_PROJECT_NAME);
    if (family) resolvedProjectId = family.id;
  }

  const task = await createTask({
    content: text.trim(),
    description: `Захвачено через AI-классификацию (kb#170): area=${classification.area.label} (${classification.area.score}), urgency=${classification.urgency.label} (${classification.urgency.score}), decompose=${classification.decompose.label} (${classification.decompose.score}).`,
    priority: URGENCY_TO_PRIORITY[classification.urgency.label],
    project_id: resolvedProjectId,
    labels,
  });

  return { task, classification };
}
