import type { ICalendarEvent, IInvitation } from "./calendar";

/** Chat request payload */
export interface IChatRequest {
  message: string;
  conversation_id?: string;
  sources?: string[];
  skill_name?: string;
}

/** Chat response from API */
export interface IChatResponse {
  conversation_id: string;
  message: string;
  matched_skill?: string;
  routing_method?: string;
  confidence?: number;
  task_id?: string;
  status: "completed" | "pending";
}

/** Tool call data within a message */
export interface IToolCallData {
  id: string;
  name: string;
  status: "pending" | "running" | "completed" | "error";
  params?: string;
  result?: string;
  error?: string;
  duration?: number;
  children?: IToolCallData[];
}

/** Single chat message */
export interface IChatMessage {
  id: string;
  role: "user" | "assistant";
  content: string;
  timestamp: string;
  matched_skill?: string;
  routing_method?: string;
  confidence?: number;
  task_id?: string;
  status?: "completed" | "pending" | "error" | "streaming";
  tool_calls?: IToolCallData[];
  thinking?: string;
  expert_id?: string;
  expert_name?: string;
  expert_color?: string;
  expert_avatar?: string;
  message_type?:
    | "chat"
    | "handoff"
    | "assist_request"
    | "plan_update"
    | "milestone"
    | "board_started"
    | "board_speech"
    | "board_summary"
    | "board_conclusion"
    | "debate_started"
    | "debate_argument"
    | "debate_summary"
    | "debate_resolved"
    | "collaboration_graph"
    | "review_result"
    | "risk_flagged"
    | "error";
  board_round?: number;
  board_role?: "moderator" | "expert" | "user" | "summary";
  plan_phases?: ITeamPlanPhase[];
  error_detail?: string;
  board_started?: IBoardStartedData;
  board_conclusion?: IBoardConcludedData;
  debate_topic?: string;
  debate_round?: number;
  debate_decision?: string;
  debate_rationale?: string;
  debate_participants?: string[];
  debate_opening?: string;
  debate_moderator?: string;
  /** U5: PM collaboration — aggregated graph data for CollaborationGraphCard */
  collaboration_graph?: ICollaborationGraphData;
  /** U5: PM collaboration — review result for ReviewResultCard */
  review_result?: IReviewResult;
  /** U5: PM collaboration — risk flag for RiskFlagCard */
  risk_flag?: IRiskFlag;
  /** U4: synthesis identifier for streaming milestone dedup (team_synthesis_chunk/team_synthesis) */
  synthesis_id?: string;
}

/** Conversation with messages */
export interface IConversation {
  id: string;
  title: string;
  messages: IChatMessage[];
  created_at: string;
  updated_at: string;
  /** 仅本地存在、尚未同步到服务端的临时会话 */
  is_local?: boolean;
  /** True if this conversation ever ran a @board meeting (board_started persisted).
   *  Backed by the server-side `is_board` field in
   *  /api/v1/portal/conversations so the sidebar can show a "私董会" badge
   *  without loading every conversation's full history. */
  is_board?: boolean;
}

/** Capability info */
export interface ICapabilityInfo {
  name: string;
  display_name: string;
  description: string;
  icon: string;
  enabled: boolean;
  skill_count: number;
}

/** Capabilities response */
export interface ICapabilitiesResponse {
  capabilities: ICapabilityInfo[];
}

/** WebSocket client message types */
export type WsClientMessage =
  | {
      type: "chat";
      message: string;
      sources?: string[];
      conversation_id?: string;
      model?: string;
    }
  | {
      type: "resume";
      task_id: string;
      conversation_id?: string;
    }
  | {
      type: "cancel";
      task_id?: string;
    }
  | {
      type: "ping";
    };

/** WebSocket server message types — matches backend portal.py protocol */
export type WsServerMessage =
  | { type: "connected"; conversation_id: string }
  | { type: "routing"; skill: string; confidence: number; method: string }
  | {
      type: "step";
      data: {
        event_type: string;
        step: number;
        data: Record<string, unknown>;
        timestamp: string;
      };
    }
  | {
      type: "result";
      data: { message?: string; content?: string; status?: string };
    }
  | { type: "error"; data: { message: string; code?: string } }
  | { type: "pong" }
  | { type: "team_formed"; data: IExpertTeamState }
  | {
      type: "expert_step";
      data: {
        expert_id: string;
        expert_name: string;
        expert_color: string;
        content: string;
        step: string;
      };
    }
  | {
      type: "expert_result_chunk";
      data: { expert_id: string; content: string };
    }
  | {
      type: "expert_result_chunk_reset";
      data: { expert_id: string; phase_id?: string };
    }
  | {
      type: "expert_result";
      data: {
        expert_id: string;
        expert_name: string;
        expert_color: string;
        content: string;
        status?: "completed" | "error";
        phase_id?: string;
        rework_attempt?: number;
        error?: string;
      };
    }
  | { type: "plan_update"; data: { plan_phases: ITeamPlanPhase[] } }
  | {
      type: "phase_started";
      data: {
        phase_id: string;
        phase_name: string;
        assigned_expert: string;
        depends_on: string[];
      };
    }
  | {
      type: "phase_completed";
      data: { phase_id: string; phase_name: string; result_summary: string };
    }
  | {
      type: "phase_failed";
      data: { phase_id: string; phase_name: string; error: string };
    }
  // PLAN_EXEC (U4) — phase lifecycle events emitted by ReActEngine.
  | { type: "phase_changed"; data: { phase: string; previous: string } }
  | {
      type: "phase_violation";
      data: {
        current_phase: string;
        tool: string;
        message: string;
        violation_kind: string;
        command_preview?: string;
      };
    }
  | {
      type: "team_synthesis_chunk";
      data: { chunk: string; synthesis_id?: string };
    }
  | {
      type: "team_synthesis";
      data: {
        content: string;
        phases_completed?: number;
        phases_total?: number;
        synthesis_id?: string;
        status?: "completed" | "error" | "cancelled";
        error?: string;
      };
    }
  | { type: "team_dissolved"; data: { team_id: string } }
  // Board Meeting 模式事件
  | { type: "board_started"; data: IBoardStartedData }
  | { type: "expert_speech"; data: IExpertSpeechData }
  | { type: "expert_speech_chunk"; data: IExpertSpeechData }
  | { type: "round_summary"; data: IRoundSummaryData }
  | { type: "user_intervention"; data: IUserInterventionData }
  | { type: "board_concluded"; data: IBoardConcludedData }
  // Debate (U5) 事件
  | { type: "debate_started"; data: IDebateStartedData }
  | { type: "expert_argument"; data: IDebateArgumentData }
  | { type: "debate_round_summary"; data: IDebateRoundSummaryData }
  | { type: "debate_resolved"; data: IDebateResolvedData }
  | { type: "team_intervention_ack"; data: { content: string } }
  // PM Collaboration (U5) 事件
  | {
      type: "collaboration_contract_defined";
      data: ICollaborationContractDefinedData;
    }
  | { type: "collaboration_notice"; data: ICollaborationNotice }
  | { type: "review_result"; data: IReviewResult }
  | { type: "risk_flagged"; data: IRiskFlag }
  // Calendar 事件 (KTD-10 — piggyback on chat WS)
  | { type: "calendar_event_created"; data: ICalendarEventCreatedData }
  | { type: "calendar_reminder"; data: ICalendarReminderData }
  | { type: "calendar_invitation"; data: ICalendarInvitationData }
  | { type: "calendar_sync_conflict"; data: ICalendarSyncConflictData };

/** Expert info within a team */
export interface IExpertInfo {
  id: string;
  name: string;
  persona: string;
  avatar: string;
  color: string;
  is_lead: boolean;
  bound_skills: string[];
  status: "active" | "inactive";
}

/** A phase within a team plan */
export interface ITeamPlanPhase {
  id: string;
  name: string;
  assigned_expert: string;
  task_description?: string;
  depends_on: string[];
  status: "pending" | "in_progress" | "completed" | "failed";
  result?: string;
  parallel_type?: "serial" | "subtask_parallel" | "competitive_parallel";
  milestone?: string;
  /** U5: PM collaboration — contracts defined by Lead for this phase */
  collaboration_contracts?: ICollaborationContract[];
  /** U5: PM collaboration — rework count after Lead review failures */
  rework_count?: number;
  /** U5: PM collaboration — Lead review feedback (modification requirements) */
  review_feedback?: string | null;
}

/** Expert team state */
export interface IExpertTeamState {
  team_id: string;
  status:
    | "forming"
    | "planning"
    | "executing"
    | "synthesizing"
    | "completed"
    | "dissolved";
  experts: IExpertInfo[];
  plan_phases: ITeamPlanPhase[];
  lead_expert: string;
  /** U2: 团队级任务目标摘要（可选，后端 team_formed 事件未发送时回退到首阶段描述） */
  task_description?: string;
}

// ── Board Meeting 模式类型 ────────────────────────────────────────────

/** Board meeting expert info (lighter than IExpertInfo) */
export interface IBoardExpert {
  name: string;
  avatar: string;
  color: string;
  is_moderator: boolean;
  persona: string;
}

/** board_started event payload */
export interface IBoardStartedData {
  team_id: string;
  topic: string;
  experts: IBoardExpert[];
  max_rounds: number;
}

/** expert_speech event payload */
export interface IExpertSpeechData {
  expert_name: string;
  expert_avatar: string;
  expert_color: string;
  content: string;
  round: number;
  role: "moderator" | "expert";
}

/** round_summary event payload */
export interface IRoundSummaryData {
  moderator_name: string;
  moderator_avatar?: string;
  moderator_color?: string;
  content: string;
  round: number;
  continue: boolean;
}

/** user_intervention event payload */
export interface IUserInterventionData {
  content: string;
  round: number;
}

/** board_concluded event payload */
export interface IBoardConcludedData {
  summary: string;
  decision_advice: string;
  total_rounds: number;
  consensus_points: string[];
  dissent_points: string[];
  error?: string;
}

// ── Debate (U5) 模式类型 ──────────────────────────────────────────────

/** debate_started event payload */
export interface IDebateStartedData {
  phase_id: string;
  phase_name: string;
  topic: string;
  participants: string[];
  max_rounds: number;
  opening: string;
}

/** expert_argument event payload */
export interface IDebateArgumentData {
  phase_id: string;
  expert_id: string;
  expert_name: string;
  expert_color: string;
  content: string;
  round: number;
  topic: string;
}

/** debate_round_summary event payload */
export interface IDebateRoundSummaryData {
  phase_id: string;
  moderator_name: string;
  content: string;
  round: number;
  continue: boolean;
}

/** debate_resolved event payload */
export interface IDebateResolvedData {
  phase_id: string;
  phase_name: string;
  decision: "adopt" | "compromise" | "shelve" | "inconclusive";
  conclusion: string;
  rationale: string;
}

// ── PM Collaboration (U5) 模式类型 ──────────────────────────────────

/** 协作契约 — 匹配后端 CollaborationContract.to_dict() */
export interface ICollaborationContract {
  from_expert: string;
  to_expert: string;
  content_description: string;
  status: "pending" | "delivered" | "received";
}

/** collaboration_contract_defined event payload
 *  (后端当前通过 plan_update 的 plan_phases[].collaboration_contracts 携带，
 *   此类型用于可能的独立事件和类型完整性) */
export interface ICollaborationContractDefinedData {
  phase_id: string;
  phase_name: string;
  contracts: ICollaborationContract[];
}

/** collaboration_notice event payload — 专家完成后按契约通知相关专家 */
export interface ICollaborationNotice {
  from_expert: string;
  to_expert: string;
  content_description: string;
  phase_id: string;
  phase_name: string;
  output_key: string;
  expert_color: string;
}

/** review_result event payload — Lead 验收阶段输出 */
export interface IReviewResult {
  phase_id: string;
  phase_name: string;
  passed: boolean;
  feedback: string;
  expert: string;
  rework_count?: number;
  final_status?: "rework" | "failed";
}

/** risk_flagged event payload — 专家风险标记 */
export interface IRiskFlag {
  expert: string;
  expert_name: string;
  risk_description: string;
  phase_id: string;
  phase_name: string;
}

/** 协作关系图聚合数据 — 存储在 collaboration_graph 消息中，随事件实时更新 */
export interface ICollaborationGraphData {
  contracts: Array<
    ICollaborationContract & { phase_id: string; phase_name: string }
  >;
  notices: ICollaborationNotice[];
  reviews: IReviewResult[];
  risks: IRiskFlag[];
}

/** Board meeting status (matches backend BoardStatus enum) */
export type BoardStatus =
  | "forming"
  | "discussing"
  | "concluding"
  | "completed"
  | "dissolved";

/** Board message entry for group chat display */
export interface IBoardMessage {
  id: string;
  expert_name: string;
  expert_avatar: string;
  expert_color: string;
  content: string;
  round: number;
  role: "moderator" | "expert" | "user" | "summary";
  timestamp: number;
}

// ── Calendar WS 事件 payload 类型 ───────────────────────────────────

/** calendar_event_created payload */
export interface ICalendarEventCreatedData {
  event: ICalendarEvent;
}

/** calendar_reminder payload */
export interface ICalendarReminderData {
  event_id: string;
  title: string;
  start_time: string;
  offset_minutes: number;
  channels: string[];
}

/** calendar_invitation payload (G6) */
export interface ICalendarInvitationData {
  invitation: IInvitation;
  event_title: string;
  inviter_name: string;
}

/** calendar_sync_conflict payload (G4) */
export interface ICalendarSyncConflictData {
  event_id: string;
  event_title: string;
  provider: string;
  local_modified: string;
  remote_modified: string;
  resolution: string;
}

/** Expert template (matches backend GET /api/v1/experts response item) */
export interface IExpertTemplate {
  name: string;
  description: string;
  is_builtin: boolean;
  avatar: string;
  color: string;
  persona: string;
  thinking_style: string;
  speaking_style: string;
  decision_framework: string;
}

/** Experts list response (matches backend GET /api/v1/experts) */
export interface IExpertsResponse {
  experts: IExpertTemplate[];
  total: number;
}

/** File upload response (matches backend POST /api/v1/chat/upload) */
export interface IUploadResponse {
  filename: string;
  stored_name: string;
  content_type: string;
  size: number;
  download_url: string;
}

/** API error */
export interface IApiError {
  status: number;
  message: string;
  detail?: string;
}

/** Task status (matches backend TaskStatus enum) */
export type TaskStatus =
  | "pending"
  | "running"
  | "completed"
  | "partially_completed"
  | "failed"
  | "cancelled";

/** Task record (matches backend TaskRecord.to_dict()) */
export interface ITaskRecord {
  task_id: string;
  agent_name: string;
  skill_name: string | null;
  input_data: Record<string, unknown>;
  status: TaskStatus;
  output_data: Record<string, unknown> | null;
  error_message: string | null;
  created_at: string;
  started_at: string | null;
  completed_at: string | null;
  progress: number;
  progress_message: string;
  metadata: Record<string, unknown>;
}
