import type { NormalizeRequestPayload, NormalizeResponsePayload, RouteHintSummary } from "./normalizer";
import type { AnswerStructureV11, EvidenceItem, InvestigationState } from "./stage1Contracts";

export type AssistantFallbackType = "none" | "out_of_scope" | "clarification" | "partial" | "unknown";
export type AssistantReplyType =
  | "factual"
  | "factual_with_explanation"
  | "partial_coverage"
  | "clarification_required"
  | "out_of_scope"
  | "empty_but_valid"
  | "no_grounded_answer"
  | "route_mismatch_blocked"
  | "backend_error";
export type RetrievalResultStatus = "ok" | "empty" | "partial" | "error";
export type RetrievalResultType = "list" | "summary" | "object" | "chain" | "ranking";
export type RetrievalConfidence = "high" | "medium" | "low";

export interface AssistantRequirement {
  requirement_id: string;
  source_fragment_id: string | null;
  requirement_text: string;
  subject_tokens: string[];
  status: "covered" | "partially_covered" | "uncovered" | "clarification_needed" | "out_of_scope";
  route: string | null;
}

export interface RequirementCoverageReport {
  requirements_total: number;
  requirements_covered: number;
  requirements_uncovered: string[];
  requirements_partially_covered: string[];
  clarification_needed_for: string[];
  out_of_scope_requirements: string[];
}

export interface AnswerGroundingCheck {
  status: "grounded" | "partial" | "no_grounded_answer" | "route_mismatch_blocked";
  route_subject_match: boolean;
  missing_requirements: string[];
  reasons: string[];
  why_included_summary: string[];
  selection_reason_summary: string[];
}

export interface FollowupStateUsageDebug {
  applied: true;
  reason: string;
  state_turn_index: number;
  context_patch: {
    period_hint_from_state: boolean;
    expected_route_from_state: boolean;
    business_context_from_state: boolean;
    question_augmented: boolean;
  };
}

export interface AssistantMessageRequestPayload {
  session_id?: string;
  user_message?: string;
  message?: string;
  mode?: "assistant" | string;
  apiKey?: string;
  model?: string;
  baseUrl?: string;
  temperature?: number;
  maxOutputTokens?: number;
  promptVersion?: string;
  systemPrompt?: string;
  developerPrompt?: string;
  domainPrompt?: string;
  fewShotExamples?: string;
  context?: NormalizeRequestPayload["context"];
  useMock?: boolean;
}

export interface UnifiedRetrievalResult {
  fragment_id: string;
  requirement_ids: string[];
  route: string;
  status: RetrievalResultStatus;
  result_type: RetrievalResultType;
  items: Array<Record<string, unknown>>;
  summary: Record<string, unknown>;
  evidence: EvidenceItem[];
  why_included: string[];
  selection_reason: string[];
  risk_factors: string[];
  business_interpretation: string[];
  confidence: RetrievalConfidence;
  limitations: string[];
  errors: string[];
}

export interface AssistantDebugPayload {
  trace_id: string;
  prompt_version: string;
  schema_version: string;
  fallback_type: AssistantFallbackType;
  route_summary: RouteHintSummary | null;
  fragments: unknown[];
  requirements_extracted: AssistantRequirement[];
  coverage_report: RequirementCoverageReport;
  routes: Array<Record<string, unknown>>;
  retrieval_status: Array<{
    fragment_id: string;
    requirement_ids: string[];
    route: string;
    status: RetrievalResultStatus;
    result_type: RetrievalResultType;
  }>;
  retrieval_results: UnifiedRetrievalResult[];
  answer_grounding_check: AnswerGroundingCheck;
  dropped_intent_segments: string[];
  followup_state_usage?: FollowupStateUsageDebug;
  answer_structure_v11: AnswerStructureV11 | null;
  investigation_state_snapshot: InvestigationState | null;
  normalized: NormalizeResponsePayload["normalized"];
}

export interface AssistantConversationItem {
  message_id: string;
  session_id: string;
  role: "user" | "assistant";
  text: string;
  reply_type: AssistantReplyType | null;
  created_at: string;
  trace_id: string | null;
  debug: AssistantDebugPayload | null;
}

export interface AssistantSessionState {
  session_id: string;
  updated_at: string;
  items: AssistantConversationItem[];
  investigation_state: InvestigationState | null;
}

export interface AssistantMessageResponsePayload {
  ok: true;
  session_id: string;
  assistant_reply: string;
  reply_type: AssistantReplyType;
  conversation_item: AssistantConversationItem;
  debug: AssistantDebugPayload;
  conversation: AssistantConversationItem[];
}
