// src/interfaces/chat-turn.ts
// Copyright (C) 2026 Rob Colbert <rob.colbert@openplatform.us>
// Licensed under the Apache License, Version 2.0

import { HydratedDocument } from "mongoose";

import type { IUser } from "./user.js";
import type { IProject } from "./project.js";
import type { IChatSession } from "./chat-session.js";
import type { IAiProvider } from "./ai-provider.js";

import { ChatSessionMode, ReasoningEffort } from "./chat-session.js";
import { GadgetId } from "../lib/gadget-id.ts";

export enum ChatTurnStatus {
  Processing = "processing",
  Finished = "finished",
  Aborted = "aborted",
  Error = "error",
}

export interface IChatTurnPrompts {
  user: string;
  system?: string;
}

export interface IChatTurnBlockThinking {
  mode: "thinking";
  createdAt: Date;
  content: string;
}

export interface IChatTurnBlockResponding {
  mode: "responding";
  createdAt: Date;
  content: string;
}

export interface IChatTurnBlockTool {
  mode: "tool";
  createdAt: Date;
  content: IChatToolCall;
}

export type IChatTurnBlock =
  | IChatTurnBlockThinking
  | IChatTurnBlockResponding
  | IChatTurnBlockTool;

export interface IChatTurnStats {
  toolCallCount: number; // total number of tool functions called this turn
  inputTokens: number; // total number of input tokens processed this turn
  thinkingTokenCount: number; // total number of thinking tokens generated this turn
  responseTokens: number; // total number of response/output tokens generated this turn
  durationMs: number; // total turn runtime in seconds
  durationLabel: string; // total turn runtime as hh:mm:ss
}

export interface IChatSubagentProcess {
  prompt: string;
  thinking?: string;
  response: string;
  toolCalls: IChatToolCall[];
  stats: IChatTurnStats;
}

export interface IChatToolCall {
  callId: string; // ID of the call so the agent can match response to call
  name: string; // tool function name being called
  parameters: string; // JSON.stringify of input parameters
  response: string; // the tool's response
  subagent?: IChatSubagentProcess; // subagent execution details, only present for subagent tool calls
}

/**
 * A chat turn is a single prompt/response pair with tool call accounting. It
 * stores all data generated by one run of the Agentic Workflow Loop by a Gadget
 * Drone process.
 */
export interface IChatTurn {
  _id: GadgetId;
  createdAt: Date;
  user: IUser | GadgetId;
  project: IProject | GadgetId;
  session: IChatSession | GadgetId;
  provider: IAiProvider | GadgetId;
  llm: string; // id/name of the model used to process the prompt
  reasoningEffort?: ReasoningEffort;
  numCtx?: number;
  mode: ChatSessionMode;
  status: ChatTurnStatus;
  prompts: IChatTurnPrompts;
  blocks: IChatTurnBlock[];
  errorMessage?: string;
  toolCalls: IChatToolCall[];
  subagents: IChatSubagentProcess[]; // subagents used while processing this turn
  stats: IChatTurnStats;
}

export type ChatTurnDocument = HydratedDocument<IChatTurn>;
