export const INVESTIGATION_STATE_SCHEMA_VERSION = "investigation_state_v1" as const;
export const ANSWER_STRUCTURE_SCHEMA_VERSION = "answer_structure_v1_1" as const;
export const ASSISTANT_EVAL_RECORD_SCHEMA_VERSION = "assistant_eval_record_v0_1" as const;
export const EVIDENCE_SOURCE_REF_SCHEMA_VERSION = "evidence_source_ref_v1" as const;

export const INVESTIGATION_MAX_EVIDENCE_REFS = 24;
export const INVESTIGATION_MAX_UNCERTAINTIES = 12;
export const INVESTIGATION_MAX_PRIMARY_ACCOUNTS = 8;
export const INVESTIGATION_MAX_REQUIREMENT_LINKS = 8;

export type InvestigationNarrowingStatus = "unknown" | "not_needed" | "applied" | "needs_clarification" | "broad_guarded";
export type InvestigationQueryModeHint = "direct_answer" | "investigation_candidate";
export type InvestigationLastAnswerMode =
  | "factual"
  | "factual_with_explanation"
  | "partial_coverage"
  | "clarification_required"
  | "out_of_scope"
  | "empty_but_valid"
  | "no_grounded_answer"
  | "route_mismatch_blocked"
  | "backend_error"
  | null;

export interface InvestigationStateFocus {
  domain: string | null;
  period: string | null;
  primary_accounts: string[];
  active_query_subject: string | null;
}

export interface InvestigationFollowupContext {
  previous_question_id: string | null;
  last_user_message: string;
  referenced_requirement_ids: string[];
}

export interface InvestigationState {
  schema_version: typeof INVESTIGATION_STATE_SCHEMA_VERSION;
  session_id: string;
  status: "idle" | "active";
  turn_index: number;
  updated_at: string;
  question_id: string | null;
  focus: InvestigationStateFocus;
  narrowing_status: InvestigationNarrowingStatus;
  evidence_refs: string[];
  open_uncertainties: string[];
  last_answer_mode: InvestigationLastAnswerMode;
  followup_context: InvestigationFollowupContext | null;
  query_mode_hint: InvestigationQueryModeHint;
}

export type EvidenceSourceNamespace = "snapshot_2020" | "assistant_derived" | "unknown";

export interface EvidencePointer {
  fragment_id: string;
  route: string;
  source: {
    namespace: EvidenceSourceNamespace;
    entity: string;
    id: string;
    period: string | null;
  };
  locator: {
    field_path: string | null;
    item_index: number | null;
  };
}

export interface EvidenceSourceRef {
  schema_version: typeof EVIDENCE_SOURCE_REF_SCHEMA_VERSION;
  namespace: EvidenceSourceNamespace;
  entity: string;
  id: string;
  period: string | null;
  canonical_ref: string;
}

export type EvidenceKind = "factual_anchor" | "aggregation" | "anomaly_signal" | "mechanism_link" | "limitation_note";
export type EvidenceConfidence = "high" | "medium" | "low";
export type EvidenceLimitationReasonCode =
  | "snapshot_only"
  | "heuristic_inference"
  | "missing_mechanism"
  | "weak_source_mapping"
  | "insufficient_detail"
  | "unknown";

export interface EvidenceLimitation {
  reason_code: EvidenceLimitationReasonCode;
  note: string | null;
}

export interface EvidenceItem {
  evidence_id: string;
  claim_ref: string;
  source_type: "retrieval_item" | "retrieval_summary" | "derived";
  source_ref: EvidenceSourceRef;
  pointer: EvidencePointer;
  evidence_kind: EvidenceKind;
  mechanism_note: string | null;
  confidence: EvidenceConfidence;
  limitation: EvidenceLimitation | null;
  payload: Record<string, unknown>;
}

export interface AnswerStructureV11 {
  schema_version: typeof ANSWER_STRUCTURE_SCHEMA_VERSION;
  answer_summary: string;
  direct_answer: string;
  mechanism_block: {
    status: "grounded" | "limited" | "unresolved";
    mechanism_notes: string[];
    limitation_reason_codes: EvidenceLimitationReasonCode[];
  };
  evidence_block: {
    evidence_ids: string[];
    source_refs?: string[];
    mechanism_notes: string[];
    coverage_note: string;
    claim_evidence_links?: Array<{
      claim_ref: string;
      evidence_ids: string[];
    }>;
  };
  uncertainty_block: {
    open_uncertainties: string[];
    limitations: string[];
  };
  next_step_block: {
    recommended_actions: string[];
    clarification_questions: string[];
  };
}

export type AssistantEvalQuestionType = "direct" | "broad" | "followup" | "multi_intent" | "clarification" | "out_of_scope";
export type AssistantEvalBroadnessLevel = "low" | "medium" | "high";
export type AssistantEvalNarrowingResult = "not_required" | "applied" | "clarification_requested" | "failed";

export interface AssistantEvalMetricVector {
  retrieval_differentiation_rate: number | null;
  generic_explanation_rate: number | null;
  accountant_actionability_score: number | null;
  false_confidence_rate: number | null;
  broad_answer_rate: number | null;
  mechanism_specificity_score: number | null;
  followup_context_retention_score: number | null;
}

export interface AssistantEvalRecord {
  schema_version: typeof ASSISTANT_EVAL_RECORD_SCHEMA_VERSION;
  created_at: string;
  case_id: string;
  scenario_tag?: string;
  session_id: string | null;
  trace_id: string | null;
  question_type: AssistantEvalQuestionType;
  broadness_level: AssistantEvalBroadnessLevel;
  narrowing_result: AssistantEvalNarrowingResult;
  evidence_quality_score: number | null;
  genericness_score: number | null;
  accountant_usefulness_score: number | null;
  accountant_metrics: AssistantEvalMetricVector;
  raw_signals?: Record<string, unknown>;
  metric_subscores?: Partial<Record<keyof AssistantEvalMetricVector, number | null>>;
  limitations?: string[];
  notes: string[];
}

export type AccountantMetricName = keyof AssistantEvalMetricVector;
export type AccountantMetricRubricScore = 0 | 1 | 2 | 3 | 4 | 5;

export interface AccountantMetricRubricBand {
  score: AccountantMetricRubricScore;
  label: string;
  description: string;
}

export const ACCOUNTANT_SCORING_RUBRIC_V01: Record<AccountantMetricName, AccountantMetricRubricBand[]> = {
  retrieval_differentiation_rate: [
    { score: 0, label: "No Differentiation", description: "Ответы почти одинаковые для разных кейсов." },
    { score: 3, label: "Partial Differentiation", description: "Различия есть, но по механизмам недостаточно стабильны." },
    { score: 5, label: "Strong Differentiation", description: "Ответы устойчиво различаются по предмету и механизму." }
  ],
  generic_explanation_rate: [
    { score: 0, label: "Mostly Generic", description: "Преобладают общие объяснения без локальной опоры." },
    { score: 3, label: "Mixed", description: "Есть и предметные, и общие блоки объяснения." },
    { score: 5, label: "Mostly Specific", description: "Объяснение в основном case-specific и операбельно." }
  ],
  accountant_actionability_score: [
    { score: 0, label: "Not Actionable", description: "Бухгалтер не получает понятного следующего шага." },
    { score: 3, label: "Partially Actionable", description: "Следующий шаг есть, но недостаточно конкретен." },
    { score: 5, label: "Actionable", description: "Есть конкретные проверяемые действия и приоритет." }
  ],
  false_confidence_rate: [
    { score: 0, label: "High False Confidence", description: "Часто дается уверенный тон при слабой опоре." },
    { score: 3, label: "Moderate False Confidence", description: "Периодически встречается избыточная уверенность." },
    { score: 5, label: "Low False Confidence", description: "Неопределенность обозначается честно и вовремя." }
  ],
  broad_answer_rate: [
    { score: 0, label: "Broad by Default", description: "Часто даются широкие ответы без controlled narrowing." },
    { score: 3, label: "Partially Controlled", description: "Broad-ответы периодически сужаются, но не всегда." },
    { score: 5, label: "Controlled", description: "Broad-ответы редки и сопровождаются корректным сужением." }
  ],
  mechanism_specificity_score: [
    { score: 0, label: "No Mechanism", description: "Есть только лейблы без механики поломки." },
    { score: 3, label: "Partial Mechanism", description: "Механизм описан частично, без полной связки." },
    { score: 5, label: "Mechanism-Aware", description: "Механизм поломки и опорные объекты связаны явно." }
  ],
  followup_context_retention_score: [
    { score: 0, label: "Context Lost", description: "Follow-up теряет фокус текущего разбора." },
    { score: 3, label: "Context Partial", description: "Фокус удерживается частично, с дрейфом." },
    { score: 5, label: "Context Retained", description: "Follow-up устойчиво держит предмет и ограничения." }
  ]
};
