// frontend/lib/types.ts
// Phase 2 backend schemas.py 와 1:1 대응하는 타입.
export type Tone = "blue" | "violet" | "coral" | "green" | "amber" | "ink" | "faint";
export type Status = "todo" | "doing" | "waiting" | "review" | "done";
export type Prio = "높음" | "보통" | "낮음";

export type { IconName } from "@/components/icons/paths";
export type { NavItem } from "@/lib/nav";

// ==================== phase-7: 결재함 + 자동화 ====================
// 주의: RiskRadar 의 Risk(interface)와 충돌 방지를 위해 RiskLevel 로 명명.
export type RiskLevel = "low" | "high";
export type ApprovalStatus = "pending" | "approved" | "executed" | "undone";
export type Autonomy = "approval_first" | "mixed" | "full_auto";
export type Cat = "mail" | "cal" | "focus" | "life";

export interface ApprovalOut {
  id: string;
  icon: string;
  tone: string;
  risk: RiskLevel;
  time: string;
  title: string;
  detail: string;
  cta: string;
  alt: string;
  undo_label: string;
  status: ApprovalStatus;
  source: string;
  rule_id: string | null;
  sort_order: number;
}
export interface ApprovalLogItem {
  id: string;
  time: string;
  text: string;
  approval_id: string | null;
}
export interface ApprovalQueue {
  autonomy: Autonomy;
  saved_today: string;
  auto_count_night: number;
  pending: ApprovalOut[];
  done: ApprovalOut[];
  log: ApprovalLogItem[];
  badges_appr: number;
}
export interface Flow {
  trigger: string;
  cond: string | null;
  action: string;
}
export interface RuleOut {
  id: string;
  name: string;
  cat: Cat;
  trigger: string;
  cond: string | null;
  action: string;
  on: boolean;
  last: string;
  runs: number;
  fresh: boolean;
  source: string;
}
export interface RuleCreate {
  name: string;
  cat: Cat;
  trigger: string;
  cond: string | null;
  action: string;
  source?: string;
}
export interface ParsePreview {
  matched: boolean;
  name: string;
  cat: Cat;
  parse: Flow;
  model: string;
  confidence: number;
}
export interface SuggestionOut {
  id: string;
  pattern: string;
  offer: Flow;
  offer_name: string;
  offer_cat: Cat;
  status: string;
}
export interface RunLogOut {
  id: string;
  time: string;
  rule: string;
  text: string;
  undone: boolean;
}
export interface AutomationPage {
  stats: { active: number; runs_week: number; saved: string };
  rules: RuleOut[];
  suggests: SuggestionOut[];
  log: RunLogOut[];
  examples: ParsePreview[];
}

export interface Person {
  id: string; // "jiwoo"
  name: string; // "지우"
  initial: string; // "지"
  color: string; // "var(--blue)" | "oklch(0.66 0.13 200)"
  is_me: boolean;
  email?: string; // phase-9 메일 발신자 주소 (PersonOut 미포함 시 undefined)
  role?: string; // phase-9 "프로덕트 디자이너" 등
}

export interface Project {
  id: string;
  folder_id: string;
  parent_id: string | null;
  name: string;
  tone: Tone;
  sort_order: number;
  pinned: boolean;
  task_count: number;
  children: Project[];
}

export interface Folder {
  id: string; // "work" | "life"
  name: string; // "업무" | "개인"
  tone: Tone;
  icon: string; // "folder" | "heart"
  sort_order: number;
  is_system: boolean;
  projects: Project[];
}

export interface TaskComment {
  id: string;
  task_id: string;
  person_id: string;
  text: string;
  created_at: string;
}

export interface Task {
  id: string;
  project_id: string;
  parent_id: string | null;
  title: string;
  status: Status;
  assignee_id: string | null;
  due: string | null; // ISO date "2026-06-08"
  prio: Prio;
  notes: string; // HTML
  est: string;
  delegated: boolean;
  sort_order: number;
  created_at: string;
  updated_at: string;
  comments: TaskComment[];
  children: Task[];
}

export interface Risk {
  kind: "지연 위험" | "업무 쏠림" | "의존성";
  icon: "clock" | "scale" | "link";
  tone: "coral" | "amber" | "violet";
  text: string; // 강조어는 **굵게** 마크다운
  task_id: string | null;
  cta: string | null;
}

export interface ScaffoldResult {
  kind: string;
  icon: string;
  items: { title: string; est: string }[];
  created: boolean;
  created_task_ids: string[];
}

// ---------- 인박스 (Phase 4) ----------
export type InboxKind = "text" | "voice" | "image";
export type InboxStatus = "new" | "classified" | "confirmed" | "dismissed";
export type RouteType = "task" | "event" | "idea";
export type Sphere = "work" | "life";

/** 백엔드 inbox_classification 1:1 */
export interface Classification {
  id: string;
  inbox_item_id: string;
  type: RouteType;
  sphere: Sphere;
  project_id: string | null;
  proj_label: string;
  tone: Tone;
  due_text: string | null;
  when_text: string | null;
  extra: string | null;
  reason: string;
  confidence: number;
  model: string;
  created_at: string;
}

/** 백엔드 inbox_item (+ 최신 classification) */
export interface InboxItem {
  id: string;
  kind: InboxKind;
  raw: string;
  status: InboxStatus;
  created_at: string;
  materialized_task_id: string | null;
  classification: Classification | null;
}

export interface CaptureResult {
  item: InboxItem;
  classification: Classification;
}

export interface ConfirmResult {
  item: InboxItem;
  task?: Task;
}

/** UI 전용: thinking/error 추가 */
export type UiInboxStatus = InboxStatus | "thinking" | "error";
export interface UiInboxItem extends Omit<InboxItem, "status"> {
  status: UiInboxStatus;
  time: string;
  fresh?: boolean;
  fallbackUsed?: boolean;
}

// ---------- 대시보드 (Phase 5) ----------
export interface DashUser {
  name: string;
  initial: string;
}
export interface Weather {
  temp: number;
  cond: string;
  icon: string;
}
export interface DashBriefing {
  today: string;
  weather: Weather;
  commute: string;
  sleep: string;
  note: string; // HTML
}
export interface ScheduleItem {
  id: string;
  time: string;
  title: string;
  tag: string;
  dur: string;
  tone: Tone;
  soon: boolean;
}
export interface ApprovalSummary {
  id: string;
  icon: string;
  tone: Tone;
  title: string;
  time: string;
}
export interface InboxRecent {
  id: string;
  kind: "text" | "voice" | "image";
  raw: string;
  type: string;
  proj_label: string;
  tone: Tone;
}
export interface DashTaskSummaryItem {
  id: string;
  title: string;
  project: string;
  prio: Prio;
}
export interface DashTaskSummary {
  open_count: number;
  items: DashTaskSummaryItem[];
}
export interface DashGoal {
  id: string;
  title: string;
  pct: number;
  sub: string;
  tone: Tone;
}
export interface Badges {
  appr: number;
  task: number;
  noti: number;
}
export interface Dashboard {
  user: DashUser;
  briefing: DashBriefing;
  saved_today: string;
  today_routed: number;
  schedule: ScheduleItem[];
  task_summary: DashTaskSummary;
  goals: DashGoal[];
  approvals_summary: ApprovalSummary[];
  inbox_recent: InboxRecent[];
  badges: Badges;
}

// ==================== phase-9: 메일 + 알림 ====================
// 메일 — 아리 분석 묶음 (백엔드 AiAnalysisOut 1:1)
export type AiTask = { text: string; project: string; due?: string; prio?: string };
export type AiEvent = {
  title: string;
  date?: string;
  day?: string;
  time?: string;
  dur?: string;
  place?: string;
};
export type AiReply = { tone: string; preview: string; body: string };
export type AiFile = { project: string; reason: string };
export type AiAnalysis = {
  summary: string;
  priority: "높음" | "보통" | "낮음";
  category: string;
  tasks: AiTask[];
  events: AiEvent[];
  replies: AiReply[];
  file: AiFile | null;
};

export type MailAccount = {
  id: string;
  name: string;
  email: string;
  tone: string;
  kind: string;
  unread: number;
};
export type MailFolder = { id: string; name: string; icon: string };
export type MailAttachment = { name: string; size: string };

// 목록 행 (가벼움). 응답 키는 'from' (백엔드 alias).
export type EmailRow = {
  id: string;
  account: string;
  from: string;
  to: string;
  subject: string;
  time: string;
  read: boolean;
  starred: boolean;
  has_attach: boolean;
  labels: string[];
  preview: string;
  ai: AiAnalysis | null;
};
// 상세 (+ date/body/attachments)
export type EmailDetail = EmailRow & {
  date: string;
  body: string[];
  attachments: MailAttachment[];
};

export type ExtractKind = "task" | "event" | "file";
export type ExtractResponse = {
  kind: ExtractKind;
  task?: Task | null;
  event_id?: string | null;
  project?: string | null;
  message: string;
};
export type ExtractAllResponse = {
  created_task_ids: string[];
  created_event_ids: string[];
  filed_project: string | null;
  message: string;
};
export type ReplyDraft = {
  to: string;
  from_account: string;
  subject: string;
  body: string;
};
export type SendRequest = {
  from_account: string;
  to: string;
  subject: string;
  body: string;
  in_reply_to?: string | null;
};
export type SendResponse = { approval_id: string; status: string; message: string };

// 알림 — 트리아지 (백엔드 NotificationOut/TriageOut 1:1)
export type NotifyBucket = "now" | "later" | "held";
export type NotifySource = "mail" | "cal" | "chat" | "fin" | "app";
export type Notification = {
  id: string;
  bucket: NotifyBucket;
  src: NotifySource;
  app: string;
  title: string;
  sum: string;
  time: string;
  why: string;
  tone: string;
  act: string;
};
export type Triage = {
  now: Notification[];
  later: Notification[];
  held: Notification[];
  counts: { now: number; later: number; held: number };
  stats: { total: number; seen: number; filtered: string };
};
export type NotifyGuard = { on: boolean; until: string; held: number; quiet: string };
export type Digest = {
  id: string;
  time: string;
  name: string;
  desc: string;
  count: number;
  done: boolean;
};
export type SenderRule = {
  id: string;
  who: string;
  from: string; // 응답 키는 'from' (백엔드 serialization_alias)
  rule: string;
  tone: string;
  bucket: NotifyBucket;
};

// ==================== phase-10: 리서치 ====================
export type RsCollection = { id: string; name: string; tone: string; n: number };
export type RsSource = {
  id: string;
  kind: "pdf" | "web" | "note";
  title: string;
  from: string; // 응답 키 'from' (백엔드 serialization_alias)
  col: string | null;
  learned: boolean;
};
export type RsEntry = { id: string; icon: string; tone: string; title: string; desc: string };
export type ResearchHome = {
  collections: RsCollection[];
  sources: RsSource[];
  prompts: string[];
  entries: RsEntry[];
};
export type RsCount = { k: string; n: number; tone: string };
export type RsCross = { src: string; tone: string; claim: string; stance: string };
export type ResearchReport = {
  id: string;
  title: string;
  asked: string;
  meta: string;
  counts: RsCount[];
  synthesis: string; // HTML
  cross: RsCross[];
  note: string;
};
export type RsRef = { title: string; part: string };
export type ResearchQA = { id: string; q: string; a: string; refs: RsRef[] };
export type RsBar = { y: string; v: number; forecast?: boolean };
export type ResearchChart = {
  id: string;
  title: string;
  asked: string;
  unit: string;
  bars: RsBar[];
  insight: string; // HTML
  caution: string;
};
export type StartResearchResult = {
  status: "ready" | "queued";
  report_id: string | null;
  report: ResearchReport | null;
  queued_text: string | null;
};
export type AskResult = {
  a: string; // HTML
  refs: RsRef[];
  grounded: boolean;
  model: string;
};

// ==================== phase-10: 여행 ====================
export type TripWeather = { d: string; t: string; icon: string };
export type TripInfo = {
  id: string;
  dday: string;
  title: string;
  dates: string;
  purpose: string;
  brief: string;
  weather: TripWeather[];
};
export type TripLeg = {
  mode: string;
  from: string;
  ft: string;
  to: string;
  tt: string;
  seat: string;
  note: string;
};
export type TripRoute = { out: TripLeg; back: TripLeg };
export type TripStayInfo = { name: string; desc: string; conf: string };
export type TripPrepItem = { text: string; state: "done" | "doing" };
export type TripDayItem = {
  t: string;
  kind: string;
  tone: string;
  title: string;
  meta: string;
  hot?: boolean;
};
export type TripDay = { id: string; tab: string; items: TripDayItem[] };
export type TripCheckItem = { id: string; text: string; auto?: string };
export type TripCheckGroup = { name: string; items: TripCheckItem[] };
export type TripExpenseRow = { name: string; amt: string; state: string };
export type TripExpense = {
  budget: number;
  planned: number;
  rows: TripExpenseRow[];
  note: string;
};
export type UpcomingTrip = {
  trip: TripInfo;
  route: TripRoute;
  stay: TripStayInfo;
  prep: TripPrepItem[];
  days: TripDay[];
  check: TripCheckGroup[];
  expense: TripExpense;
};
export type SavedTrip = {
  id: string;
  title: string;
  tag: string;
  note: string;
  now: string;
  delta: string;
  down: boolean;
  watch: boolean;
  hint: string;
  spark: number[];
};
export type PlanTransport = {
  mode: string;
  name: string;
  desc: string;
  price: string;
  pick?: boolean;
  note?: string;
};
export type PlanStay = {
  name: string;
  desc: string;
  price: string;
  unit: string;
  pick?: boolean;
};
export type PlanDayItem = { t: string; title: string; tone: string };
export type PlanDay = { tab: string; items: PlanDayItem[] };
export type PlanBudgetRow = { name: string; amt: string };
export type PlanBudget = { total: string; cap: string; rows: PlanBudgetRow[] };
export type PlanResearchStep = { icon: string; label: string; detail: string };
export type PlanResult = {
  id: string;
  idx: number;
  custom: boolean;
  title: string;
  meta: string;
  summary: string; // HTML
  weather: string;
  transport: PlanTransport[];
  stay: PlanStay[];
  days: PlanDay[];
  budget: PlanBudget;
  checklist: string[];
  sources: string[];
  research?: PlanResearchStep[] | null;
};

// ==================== phase-11: 라이프 케어 (건강·금융·지식) ====================
export type LifeDomain = "health" | "finance" | "knowledge";
export type LifeInsightKind = "alert" | "save" | "info";
export type LifeKnowledgeType = "article" | "note" | "idea" | "highlight";

export interface ConnectorSourceOut {
  id: string;
  domain: LifeDomain;
  name: string;
  kind: string;
  tone: string;
  on: boolean;
  last: string;
}

// ---- 건강 ----
export interface RingOut {
  label: string;
  val: string;
  unit: string;
  goal: string;
  pct: number;
  icon: string;
  tone: string;
}
export interface VitalOut {
  label: string;
  val: string;
  unit: string;
  trend: string; // "up" | "down" | "flat"
  note: string;
  tone: string;
}
export interface SleepStageOut {
  label: string;
  pct: number;
  tone: string; // "muted" 는 var(--card-3)/var(--faint)
}
export interface SleepOut {
  total: string;
  score: number;
  stages: SleepStageOut[];
  week: number[];
  note: string;
}
export interface HabitOut {
  id: string;
  title: string;
  goal: string;
  done: number;
  total: number;
  streak: number;
  icon: string;
  tone: string;
  at: string;
  automation_rule_id?: string | null;
}
export interface HealthOut {
  rings: RingOut[];
  vitals: VitalOut[];
  sleep: SleepOut;
  coach: string; // HTML
  habits: HabitOut[];
}

// ---- 금융 ----
export interface BudgetOut {
  spent: number;
  limit: number;
  pct: number;
  delta_pct: number;
  days_left: number;
}
export interface CategoryOut {
  name: string;
  amt: number;
  pct: number;
  icon: string;
  tone: string;
  over: boolean;
}
export interface SubOut {
  id: string;
  name: string;
  date: string;
  in_days: number;
  amt: number;
  icon: string;
  tone: string;
  note: string;
  paused: boolean;
}
export interface InsightOut {
  id: string;
  kind: LifeInsightKind;
  icon: string;
  title: string;
  body: string;
  action: string; // "pause_sub" | "raise_budget" | "auto_transfer" | ""
  action_ref: string;
}
export interface FinanceOut {
  budget: BudgetOut;
  cats: CategoryOut[];
  subs: SubOut[];
  coach: string; // HTML
  insights: InsightOut[];
}

// ---- 지식 ----
export interface CollectionOut {
  name: string;
  count: number;
  tone: string;
}
export interface KnowledgeItemOut {
  id: string;
  type: LifeKnowledgeType;
  title: string;
  src: string;
  time: string;
  tone: string;
  icon: string;
  tags: string[];
  excerpt: string;
  ai: string; // HTML
}
export interface KnowledgeStatsOut {
  items: number;
  this_week: number;
  collections: number;
}
export interface KnowledgeOut {
  stats: KnowledgeStatsOut;
  suggested: string[];
  collections: CollectionOut[];
  items: KnowledgeItemOut[];
}

// ---- 통합 overview ----
export interface LifeOverviewOut {
  sources: Record<LifeDomain, ConnectorSourceOut[]>;
  health: HealthOut;
  finance: FinanceOut;
  knowledge: KnowledgeOut;
}

// ---- 액션 응답 ----
export interface HabitTickResponse {
  habit: HabitOut;
}
export interface SubPauseResponse {
  sub: SubOut;
  approval_id?: string | null;
}
export interface InsightActResponse {
  approval_id?: string | null;
  task_id?: string | null;
  message: string;
}
export interface KnowledgeAskResponse {
  q: string;
  body: string; // HTML
  sources: string[];
}
export interface KnowledgeSuggestActResponse {
  task_id?: string | null;
  event_id?: string | null;
  message: string;
}

// ==================== phase-12 여정(journey) ====================
export type JourneyPerson = {
  id: string;
  name: string;
  initial: string;
  color: string;
  me: boolean;
  tasks: number;
  role: string;
};
export type JourneyStage = { id: string; title: string; time: string; tone: string; n: string };
export type RoutineCard = {
  node: string;
  icon: string;
  title: string;
  meta: string;
  tag: string;
  tool: string;
  toolTone: string;
};
export type TaskCard = { node: string; title: string; meta: string; who: string; done: boolean };
export type MeetCard = {
  node: string;
  time: string;
  title: string;
  meta: string;
  who: string;
  soon: boolean;
};
export type TileCard = { node: string; hi: boolean; icon: string; tt: string; ts: string };
export type JourneyCards = { s1: RoutineCard[]; s2: TaskCard[]; s3: MeetCard[]; s4: TileCard[] };
export type JourneyLink = { from_node: string; to_node: string; tone: string; dash: boolean };
export type JourneyRow = {
  node: string;
  title: string;
  star: boolean;
  statusKey: string;
  statusLabel: string;
  startTime: string;
  who: string;
};
export type JourneyGauge = {
  pct: number;
  tone: string;
  val: string;
  unit: string;
  label: string;
  sub: string;
};
export type Journey = {
  header: { dateLabel: string; weather: string };
  meta: { stageCount: number; itemCount: number; collabCount: number; peopleMore: string };
  people: JourneyPerson[];
  stages: JourneyStage[];
  cards: JourneyCards;
  links: JourneyLink[];
  rows: JourneyRow[];
  table: { subtitle: string };
  gauges: JourneyGauge[];
  gaugeFoot: string;
};

// ==================== phase-13 외부 연동(connectors) ====================
// 백엔드 키 snake_case 유지 (env_mode/last_synced_at/error_detail/events_published/account_id).
// NOTE: 위 phase-11 ConnectorSourceOut 과는 별개 — 그 타입은 건드리지 않는다.
export type ConnState = "connected" | "disconnected" | "syncing" | "error" | "token_expired";

export interface ConnectorStatus {
  id: string;
  domain: "mail" | "calendar" | "chat" | "finance" | "health" | "knowledge";
  provider: string;
  name: string;
  kind: string;
  tone: "blue" | "violet" | "coral" | "green" | "amber" | "ink" | "faint";
  mode: "mock" | "csv" | "healthkit" | "real";
  env_mode: string;
  state: ConnState;
  on: boolean;
  last: string;
  last_synced_at: string | null;
  error_detail: string;
}
export interface OAuthStart {
  authorize_url: string;
}
export interface SyncResult {
  domain: string;
  account_id: string;
  seen: number;
  upserted: number;
  skipped: number;
  errors: number;
  events_published: string[];
  detail: string;
}
export interface ImportResult {
  entity_type: string;
  imported: number;
  skipped: number;
  errors: number;
  detail: string;
}

// ==================== phase-14: 능동 에이전트 + 멀티모달 ====================
// 백엔드 schemas.py(§4.2)와 1:1. snake_case 키 유지.
export type ErrandKind = "booking" | "refund" | "cancel" | "support";
export type ErrandStatus =
  | "planning"
  | "running"
  | "awaiting_approval"
  | "done"
  | "failed"
  | "cancelled";
export type StepState = "pending" | "running" | "done" | "blocked" | "error";

export interface ErrandStep {
  id: string;
  seq: number;
  phase: "plan" | "act" | "observe" | "reflect";
  tool: string | null;
  label: string;
  detail: string | null;
  external_effect: boolean;
  state: StepState;
}
export interface ErrandTask {
  id: string;
  kind: ErrandKind;
  title: string;
  goal: string;
  target: string | null;
  tone: Tone;
  status: ErrandStatus;
  approval_id: string | null;
  result_summary: string | null;
  model: string;
  steps: ErrandStep[];
}
export interface ProactiveCard {
  id: string;
  kind: "schedule" | "finance" | "focus" | "health" | "digest";
  icon: string;
  tone: Tone;
  title: string;
  why: string;
  cta: string | null;
  action_kind: "focus_block" | "task" | "automation" | "approval" | "none" | null;
  detected_at: string;
  status: "active" | "accepted" | "dismissed";
}
export interface WeeklyReviewPattern {
  title: string;
  suggest: string;
  action_kind: string;
  payload: unknown;
}
export interface WeeklyReview {
  id: string;
  week_label: string;
  deep_work_h: number;
  meeting_h: number;
  done_count: number;
  auto_count: number;
  saved_minutes: number;
  patterns: WeeklyReviewPattern[];
  note: string | null;
}
export interface TranscribeResult {
  text: string;
  seconds: number;
  model: string;
  confidence: number;
}
export interface CaptionResult {
  text: string;
  ocr: string;
  model: string;
  confidence: number;
}
export interface ProactiveAcceptResult {
  id: string;
  action_kind: string;
  created_id: string | null;
  message: string;
}
export interface WorkerRunResult {
  job: string;
  ok: boolean;
  detail: string;
}

// phase-15 인증: GET /api/me / POST /api/auth/login 응답(MeOut)
export type Me = {
  id: string;
  name: string;
  initial: string;
  email: string;
  role: string; // member | admin | 자유 텍스트(프로필 편집)
};

// ==================== 설정(settings) ====================
export type LlmProvider = "auto" | "ollama" | "heuristic";

export interface LlmConfig {
  provider: LlmProvider;
  model: string;
  host: string;
  timeout: number;
  provider_options: LlmProvider[];
  overridden: boolean;
  embed_provider: string;
  embed_model: string;
  agent_provider: string;
  stt_provider: string;
  vision_provider: string;
}

export interface LlmUpdate {
  provider?: string;
  model?: string;
  host?: string;
  timeout?: number;
}

export interface LlmTestResult {
  reachable: boolean;
  provider: string;
  model: string;
  host: string | null;
  models: string[];
  detail: string;
}

export interface SystemConfig {
  env: string;
  auth_enabled: boolean;
  worker_enabled: boolean;
  database: string;
  sync_interval_minutes: number;
  sync_page_size: number;
  web_search_provider: string;
  connector_modes: Record<string, string>;
}

export interface TokenInfo {
  id: string;
  name: string;
  created_at: string;
  last_used_at: string | null;
  revoked: boolean;
}

export interface TokenCreated {
  id: string;
  name: string;
  token: string | null;
  created_at: string;
}
