// ─── Investigation Types ──────────────────────────────────────────────────────
// Plant Investigations: persistent case records that evolve over time.
// Each Investigation is a container for photos, symptoms, AI findings,
// timeline events, and future treatment plans.

export type InvestigationStatus = 'open' | 'monitoring' | 'resolved' | 'archived';

export type InvestigationPhotoCategory =
  | 'area_of_concern'
  | 'whole_plant'
  | 'soil'
  | 'setup'
  | 'environment'
  | 'close_up';

export type InvestigationPhoto = {
  uri: string;
  category: InvestigationPhotoCategory;
  addedAt: string;
};

export type InvestigationTimelineEventType =
  | 'created'
  | 'photos_added'
  | 'symptoms_recorded'
  | 'first_look_generated'
  | 'note_added'
  | 'status_changed'
  | 'plant_linked';

export type InvestigationTimelineEvent = {
  id: string;
  type: InvestigationTimelineEventType;
  timestamp: string;
  detail?: string;
};

export type FirstLook = {
  summary: string;
  possibleCauses: string[];
  noticed: string[];
  suggestedChecks: string[];
  confidence: 'low' | 'medium' | 'high';
  uncertaintyNote: string;
  generatedAt: string;
};

/**
 * A single "point" (visit) in a case. A plant has ONE open case at a time;
 * each problem scan appends a new point to that case. A point captures one
 * scan's photos, symptoms, notes, and Pixie's first look.
 */
export type InvestigationPoint = {
  pointId: string;
  createdAt: string;
  symptoms: string[];
  notes?: string;
  photos: InvestigationPhoto[];
  firstLook?: FirstLook;
  possibleCauses: string[];
  suggestedChecks: string[];
};

/**
 * A treatment step in the "pills the doctor prescribed." Each step that has a
 * due date gets emitted as a Care-tab task with source 'diagnosis'.
 */
export type TreatmentStep = {
  stepId: string;
  action: string;                       // "Apply neem oil to affected leaves"
  instructions: string[];               // step-by-step
  dueOffsetDays: number;                // 0 = do now; N = due in N days
  safetyWarnings: string[];             // e.g. "don't harvest/eat for 72h"
  kind: 'treatment' | 'recheck';        // recheck = the appointment reminder
  /** What materials the gardener needs for this step (e.g. "neem oil", "spray bottle").
   *  Used to flag which supplies they may need to acquire before treating. */
  materials?: string[];
  /** Quick-pick "what did you use" options for this step (Bekky, 2026-09-02).
   *  Returned by the AI at diagnosis time, alongside `materials`. Tapping a chip
   *  in the case-treatment modal records it as this step's `usedProduct` without
   *  free-typing. Absent = fall back to free-text only. */
  chips?: string[];
};

/**
 * A single execution (or conscious SKIP) of a treatment step, recorded when the
 * user completes or skips that step from the case-treatment modal (Bekky,
 * 2026-09-02). Append-only record on the case so the AI can learn *what the
 * gardener actually did* (the magic-bullet capture) and *what they chose not
 * to do* — a skip is as informative as a completion ("waiting on neem oil in
 * the mail" is different from "never addressed it").
 */
export type StepExecution = {
  stepId: string;
  status: 'done' | 'skipped';
  /** Local ISO timestamp when the user acted on this step. */
  recordedAt: string;
  /** What the user actually used (from a chip tap or free text). Optional —
   *  a step can be checked off with no product capture. */
  usedProduct?: string;
  /** Free-text note (optional, never required — reasons are the user's own). */
  note?: string;
  /** Outcome signal, ONLY for 2nd+ completed treatment in a case (Bekky,
   *  2026-09-02): you can't judge "did it help" after the first treatment.
   *  Absent on first-treatment and always absent on skips. */
  outcome?: 'better' | 'same' | 'worse';
};

/**
 * The full treatment plan returned with a diagnosis (Option A — one AI call).
 */
export type TreatmentPlan = {
  planId: string;
  generatedAt: string;
  steps: TreatmentStep[];               // emitted as care tasks
  recheckDays?: number;                 // "see me next week" → recheck due in N days
  generalNote?: string;                 // e.g. "Give it neem, see me next week."
};

/**
 * A single check-in on an open case: a progress photo + 3-way change signal +
 * optional short chips (Second-Look path) + Pixie's assessment + refined next step.
 * Separate from points[] (visits) — this is a lighter follow-up, not a full scan.
 */
export type ProgressUpdate = {
  progressId: string;
  createdAt: string;
  entryType: 'scheduled' | 'early';     // came back at appointment vs early/worried
  betterOrWorse: 'better' | 'same' | 'worse';
  note?: string;
  photoUri: string;
  referenceIntakeUris?: string[];       // matched intake photo(s); may be []
  optionalChips?: string[];             // Second-Look path only, short set
  aiAssessment?: {
    summary: string;
    working: 'improving' | 'no_change' | 'worsening' | 'unknown';
    nextStep?: TreatmentStep;           // refined next step (fetched here)
    planAdjusted?: boolean;
    recheckDays?: number;               // new recheck if changed
  };
};

export type Investigation = {
  investigationId: string;
  plantId?: string;
  title: string;
  status: InvestigationStatus;
  createdAt: string;
  updatedAt: string;
  symptoms: string[];
  notes: string;
  photos: InvestigationPhoto[];
  firstLook?: FirstLook;
  possibleCauses: string[];
  suggestedChecks: string[];
  /** One scan per point — the case's history of visits. Backfilled from the
   *  legacy flat fields on load for older cases. */
  points: InvestigationPoint[];
  /** The treatment plan prescribed at diagnosis — drives the care tasks. */
  treatmentPlan?: TreatmentPlan;
  /** Per-step execution/skip record (Bekky, 2026-09-02). Append-only: every time
   *  the user completes OR skips a treatment step (via the case-treatment modal),
   *  one entry is added. Lets the case + AI know what was actually used/done and
   *  what was consciously skipped. Absent on old cases (default []). */
  stepExecutions?: StepExecution[];
  /** The case's check-in history (progress photos + assessments). */
  progressUpdates: ProgressUpdate[];
  /** pointIds of collapsed visits (Bekky, 2026-08-16) — persisted per-case so a
   *  visit's collapse state survives app restarts. Additive; absent on old cases. */
  collapsedPoints?: string[];
  linkedMemories: string[];
  linkedAiFindings: string[];
  timeline: InvestigationTimelineEvent[];
};
