/**
 * cc-soul — Shared type definitions
 *
 * All interfaces extracted from handler.ts + new foundation types.
 */

// ═══════════════════════════════════════════════════════════════════════════════
// CONFIG
// ═══════════════════════════════════════════════════════════════════════════════

export interface SoulConfig {
  notify_webhook?: string  // optional: POST notifications to this URL
  sync?: SyncConfig
}

// ═══════════════════════════════════════════════════════════════════════════════
// BRAIN EXPERIENCE
// ═══════════════════════════════════════════════════════════════════════════════

export interface Experience {
  response: string
  confidence: number
  used: number
  negCount: number
  lastUsed: number
  created: number
}

// ═══════════════════════════════════════════════════════════════════════════════
// BODY STATE
// ═══════════════════════════════════════════════════════════════════════════════

export interface BodyState {
  energy: number // 0-1, depletes on work, recovers over time
  mood: number // -1 to 1, negative=bad positive=good
  load: number // 0-1, current cognitive load
  alertness: number // 0-1, raised by corrections
  anomaly: number // 0-1, sense of something wrong
}

// ═══════════════════════════════════════════════════════════════════════════════
// COGNITION
// ═══════════════════════════════════════════════════════════════════════════════

export interface IntentSpectrum {
  information: number   // 信息需求："我想知道..."
  action: number        // 行动需求："帮我做..."
  emotional: number     // 情感需求："我好烦..."
  validation: number    // 验证需求："这样对吗..."
  exploration: number   // 探索需求："有没有更好的..."
}

export interface EntropyFeedbackResult {
  entropy: number
  signal: 'engaged' | 'passive' | 'disengaged'
}

export interface CogResult {
  hints: string[]
  intent: string
  strategy: string
  attention: string
  complexity: number
  spectrum?: IntentSpectrum
  entropyFeedback?: EntropyFeedbackResult
}

/** CGAF: Cognition-Gated Activation Field — Bayesian 概率到信号权重的桥梁 */
export interface CogHints {
  correctionProb: number   // 0-1, Bayesian gate
  emotionalProb: number    // 0-1
  technicalProb: number    // 0-1
  casualProb: number       // 0-1
  complexity: number       // 0-1
  spectrum?: IntentSpectrum // 5维意图向量
}

// ═══════════════════════════════════════════════════════════════════════════════
// MEMORY
// ═══════════════════════════════════════════════════════════════════════════════

export interface Memory {
  content: string
  scope: string // preference | fact | event | opinion | topic | correction | dream | curiosity | reflection | proactive | discovery | task | reflexion | gratitude | visual
  ts: number
  relevance?: number // computed on recall
  emotion?: string // neutral | warm | important | painful | funny
  userId?: string // who created this memory
  tags?: string[] // semantic tags generated by CLI for tag-based recall
  visibility?: 'global' | 'channel' | 'private' // memory visibility scope
  channelId?: string // channel where this memory was created
  confidence?: number    // 0-1, starts at 0.7, boosted on access, degraded on contradiction
  lastAccessed?: number  // timestamp of last recall
  validFrom?: number     // when this fact became true (timestamp)
  validUntil?: number    // when this fact stopped being true (0 = still valid)
  // ── Time-decay tiered memory fields ──
  tier?: 'short_term' | 'mid_term' | 'long_term' | 'fading' | 'gist' | 'absorbed'  // lifecycle stage (default: short_term)
  recallCount?: number   // how many times this memory has been recalled
  lastRecalled?: number  // timestamp of last recall
  recallContexts?: string[]  // reconsolidation: contexts in which this memory was recalled
  // ── Semantic versioning: previous versions of this memory ──
  history?: { content: string; ts: number }[]
  // ── Chain-of-Thought reasoning trace ──
  reasoning?: {
    context: string      // 触发这条记忆的上下文
    conclusion: string   // 结论
    confidence: number   // 推理置信度 0-1
  }
  // ── Situational context at creation time ──
  situationCtx?: {
    attention?: string   // technical/emotional/casual/correction
    intent?: string      // wants_opinion/wants_action/wants_answer
    mood?: number        // body.mood at creation (-1 to 1)
    energy?: number      // body.energy at creation (0-1)
  }
  // ── Source tracking (防幻觉：区分用户亲口说的 vs AI 自己推断的) ──
  source?: 'user_said' | 'ai_inferred' | 'ai_observed' | 'system'
  // ── Emotional intensity at creation (高情绪记忆衰减更慢) ──
  emotionIntensity?: number  // 0-1, used by smart-forget to slow decay
  // ── 闪光灯记忆（Flashbulb Memory）：高情绪事件深度编码 ──
  flashbulb?: {
    surroundingContext: string  // 前后对话摘要
    bodyState: { mood: number; energy: number }  // 创建时的身体状态
    mentionedPeople: string[]  // 当时提到的人
    detailLevel: 'full'        // 标记：不压缩，永久保留原文
  }
  importance?: number    // 1-10, 预期违背评分 (surprise score)
  surprise?: number      // 同 importance，别名
  because?: string           // causal reason: WHY this decision/preference was made
  // ── Bayesian confidence: Beta distribution parameters ──
  bayesAlpha?: number        // Beta α (default 2), incremented on positive evidence
  bayesBeta?: number         // Beta β (default 1), incremented on negative evidence
  // ── FSRS-4.5 spaced repetition state (replaces Weibull for new memories) ──
  fsrs?: { stability: number; difficulty: number; reps: number; lapses: number }
  // ── Living Memory Network: micro-links accumulated from recall co-occurrences ──
  microLinks?: { query: string; memoryRef: string; sharedKeywords: string[]; ts: number }[]
  // ── Prospective Tags: AAM 预测的未来查询词（写入时生成，零 LLM doc2query）──
  prospectiveTags?: string[]
  // ── P1a: Memory-level injection competition ──
  injectionEngagement?: number  // 被注入后用户 engaged 的次数（trigram overlap > 0.3）
  injectionMiss?: number        // 被注入后用户 ignored 的次数（trigram overlap < 0.1）
  // ── P2a: 日期双写（懒生成）──
  contentNormalized?: string    // 日期归一化版本（"昨天" → "2026-03-30"）。召回/注入用此字段
  // ── 记忆唯一 ID ──
  memoryId?: string  // 创建时生成，永不变

  // ── 记忆溯源链（Memory Lineage）──
  lineage?: Array<{
    action: 'created' | 'reshaped' | 'compressed' | 'gisted' | 'promoted' | 'demoted' | 'merged' | 'superseded'
    ts: number
    trigger?: string
    delta?: string
    from?: number
    to?: number
  }>

  // ── 事实版本链（Fact Supersession Chain）──
  supersedes?: string      // 本记忆取代了哪条旧记忆的 memoryId
  supersededBy?: string    // 本记忆被哪条新记忆取代的 memoryId

  // ── Hindsight 认知网络分类 ──
  network?: 'world' | 'experience' | 'opinion' | 'entity'
  // ── 前瞻锚定（Prospective Anchoring）──
  prospective?: {
    trigger: string
    expiresAt: number
    action: string
  }
  // ── P0a: Graveyard metadata ──
  _graveyardOriginalScope?: string
  _graveyardTs?: number
  _needsVerification?: boolean
  _complementOf?: string[]  // 互补候选的 memoryId 列表（写入时标记，heartbeat 消费）
  _preheated?: boolean  // 预测性预热标记（heartbeat 设置，recall 后清除）
  _segmentId?: number   // 话题河流：同一段对话中的记忆共享 segmentId
  _entityIds?: string[] // 写入时由 findMentionedEntities 提取的实体名列表（slotization 用）
  _eventDate?: number   // 事件发生的原始时间戳（区别于 ts 的归一化时间）
  utility?: number  // -5 to +5, default 0. MemRL: "did this memory help?"
  _matchScore?: number  // activation-field 计算的匹配分数（运行时临时字段）
  _gist?: { polarity: number; abstractTags: string[] }  // benchmark gist 摘要（运行时临时字段）
}

// ═══════════════════════════════════════════════════════════════════════════════
// STRUCTURED FACTS — key-value triples extracted from natural language memories
// Mem0-style fact store for precise queries ("用户喜欢什么语言？" → Python)
// ═══════════════════════════════════════════════════════════════════════════════

export interface StructuredFact {
  subject: string       // "user" | entity name
  predicate: string     // "likes" | "works_at" | "uses" | "dislikes" | "has" | "prefers" | "lives_in"
  object: string        // the value
  confidence: number    // 0-1
  source: 'user_said' | 'ai_inferred' | 'ai_observed'
  ts: number            // when extracted
  validUntil: number    // 0 = still valid, >0 = expired at this time
  memoryRef?: string    // link to original Memory content (first 60 chars)
  segmentId?: number    // 话题河流：关联到对应的对话段（P1 fix）
  supersedes?: string   // 事实版本链：本事实取代的旧 object 值
}

// ═══════════════════════════════════════════════════════════════════════════════
// USER PROFILE
// ═══════════════════════════════════════════════════════════════════════════════

export interface UserRhythm {
  activeHours: number[]           // histogram of message counts per hour (24 slots)
  weekdayTopics: string[]         // frequent weekday topics
  weekendTopics: string[]         // frequent weekend topics
  avgResponseDelay: number        // avg seconds between user messages
  lastMessageTs: number           // timestamp of last message
}

export interface UserProfile {
  userId: string
  displayName: string
  tier: 'owner' | 'known' | 'new' // auto-detected
  messageCount: number
  corrections: number
  lastSeen: number
  firstSeen: number
  topics: string[] // this user's frequent topics
  style: 'technical' | 'casual' | 'mixed' // auto-detected from message patterns
  rhythm?: UserRhythm
  // Relationship dynamics
  trust: number             // 0-1, how much user trusts cc's answers
  familiarity: number       // 0-1, how well cc knows this user
  relationshipTrend: 'improving' | 'stable' | 'declining'
  lastConflict: number      // timestamp of last correction/disagreement
  sharedEpisodes: number    // count of completed conversations together
  personaHistory?: { persona: string; count: number }[]  // persona usage tracking
  language?: string  // auto-detected: 'zh', 'en', 'ja', 'ko', 'es', 'fr', 'de', 'ru', etc.
  bio?: string       // user self-description: occupation, expertise, interests — extracted from conversation
  languageDna?: { topWords: Record<string, number>; avgLength: number; samples: number }
}

// ═══════════════════════════════════════════════════════════════════════════════
// RULES & EVOLUTION
// ═══════════════════════════════════════════════════════════════════════════════

export interface Rule {
  rule: string
  source: string // what triggered this rule
  ts: number
  hits: number // how many times this rule was relevant
  matchedCount?: number         // how many times this rule was injected into a prompt
  matchedQualitySum?: number    // sum of quality scores when this rule was present
  // ── Causal context: WHY this rule exists and WHEN it applies ──
  cause?: string                // what caused this rule ("用户纠正了我的ARM64指令解释")
  conditions?: string[]         // when this rule applies (["technical", "ARM64", "assembly"])
  invalidatedBy?: string        // what would make this rule obsolete
}

export interface Hypothesis {
  id: string
  description: string // "when user asks X, strategy Y works better"
  alpha: number       // Beta distribution α (prior: 1, +1 on success)
  beta: number        // Beta distribution β (prior: 1, +1 on failure)
  status: 'active' | 'verified' | 'rejected'
  created: number
  evidence_for?: number    // legacy, kept for migration
  evidence_against?: number // legacy, kept for migration
  verifyCount?: number     // consecutive successful verifications
}

// ═══════════════════════════════════════════════════════════════════════════════
// ENTITY GRAPH
// ═══════════════════════════════════════════════════════════════════════════════

export interface Entity {
  name: string
  type: string // person | project | company | tech | place
  attrs: string[]
  firstSeen: number
  mentions: number
  valid_at: number      // creation timestamp (legacy data defaults to 0)
  invalid_at: number | null  // invalidation timestamp (null = still valid)
  activation?: number        // 0-1, dynamic energy from recent mentions (spreading activation)
  lastActivatedAt?: number   // timestamp of last activation boost
}

export interface Relation {
  source: string
  target: string
  type: string // works_at | uses | knows | part_of | related_to | caused_by | depends_on | triggers | learned_from | prefers_over
  ts: number
  valid_at: number      // creation timestamp (legacy data defaults to 0)
  invalid_at: number | null  // invalidation timestamp (null = still valid)
  weight?: number       // relation strength, default 1.0
  confidence?: number   // trust level 0-1, default 0.7
}

// ═══════════════════════════════════════════════════════════════════════════════
// INTERACTION STATS
// ═══════════════════════════════════════════════════════════════════════════════

export interface InteractionStats {
  totalMessages: number
  firstSeen: number
  corrections: number
  positiveFeedback: number
  tasks: number
  topics: Set<string>
  driftCount: number
}

// ═══════════════════════════════════════════════════════════════════════════════
// INNER LIFE
// ═══════════════════════════════════════════════════════════════════════════════

export interface JournalEntry {
  time: string
  thought: string
  type: 'observation' | 'reflection' | 'concern'
}

// ═══════════════════════════════════════════════════════════════════════════════
// FOLLOW-UP & PLANNING
// ═══════════════════════════════════════════════════════════════════════════════

export interface FollowUp {
  topic: string
  when: number // timestamp when to follow up
  asked: boolean
}

export interface Plan {
  goal: string
  steps: { id: number; desc: string; status: 'pending' | 'running' | 'done' | 'failed' }[]
  createdAt: number
}

export interface Workflow {
  name: string
  trigger: string // trigger condition description
  steps: string[] // step list (each step is a CLI prompt)
  schedule?: string // cron expression (optional)
  lastRun: number
  runCount: number
}

// ═══════════════════════════════════════════════════════════════════════════════
// SKILL FACTORY
// ═══════════════════════════════════════════════════════════════════════════════

export interface RequestPattern {
  keywords: string[]
  count: number
  lastSeen: number
  example: string // most recent full request
  skillCreated: boolean
}

// ═══════════════════════════════════════════════════════════════════════════════
// EPISTEMIC (Knowledge Boundary)
// ═══════════════════════════════════════════════════════════════════════════════

export interface DomainConfidence {
  domain: string           // "python" | "ios-reverse" | "图片识别" | "闲聊" etc
  totalResponses: number
  qualitySum: number
  corrections: number
  avgQuality: number       // computed
  correctionRate: number   // computed
}

// ═══════════════════════════════════════════════════════════════════════════════
// EVAL
// ═══════════════════════════════════════════════════════════════════════════════

export interface EvalMetrics {
  totalResponses: number
  avgQuality: number
  correctionRate: number
  brainHitRate: number
  memoryRecallRate: number
  lastEval: number
}

// ═══════════════════════════════════════════════════════════════════════════════
// SELF-UPGRADE
// ═══════════════════════════════════════════════════════════════════════════════

export interface UpgradeLogEntry {
  date: string
  change: string
  reason: string
  type: 'rule' | 'code' // rule=old pattern add rule, code=actual code change
}

export interface UpgradeExperience {
  id?: string            // unique ID for stable callback reference (date_timestamp)
  date: string
  description: string
  targetModule: string
  outcome: 'success' | 'rolled_back' | 'failed'
  metricsImpact: string  // "+15% recall" or "correction rate +3%, rolled back"
  lesson: string         // "改独立模块比改 handler.ts 安全"
}

export interface UpgradeState {
  phase: 'idle' | 'pending_confirm' | 'executing' | 'observing'
  analysis: string
  proposals: { change: string; reason: string; scope: string }[]
  designedAt: number
  observationStart: number
  observationExtensions: number // how many times observation was extended due to insufficient data
  preUpgradeEval: EvalMetrics | null
  preWindowStats: { messages: number; corrections: number; qualitySum: number; qualityCount: number }
  backupPath: string
  appliedDiff: string // recorded diff of actual changes
}

// ═══════════════════════════════════════════════════════════════════════════════
// TASK DELEGATION
// ═══════════════════════════════════════════════════════════════════════════════

export interface PendingTask {
  taskDoc: string
  userPrompt: string
  ts: number
}

// ═══════════════════════════════════════════════════════════════════════════════
// CHAT HISTORY
// ═══════════════════════════════════════════════════════════════════════════════

export interface ChatTurn {
  user: string
  assistant: string
  ts: number
}

// ═══════════════════════════════════════════════════════════════════════════════
// NEW FOUNDATION TYPES
// ═══════════════════════════════════════════════════════════════════════════════

export interface PostResponseResult {
  memories: { content: string; scope: string; visibility?: 'global' | 'channel' | 'private' }[]
  memoryOps?: { action: 'update' | 'delete'; keyword: string; reason: string; newContent?: string }[]
  entities: { name: string; type: string; relation?: string }[]
  satisfaction: 'POSITIVE' | 'NEUTRAL' | 'NEGATIVE' | 'TOO_VERBOSE'
  quality: { score: number; issues: string[] }
  emotion: string
  reflection: string | null
}

export interface Augment {
  content: string
  priority: number // higher = more important (1-10)
  tokens: number // estimated token count
  // ── EvidencePack-lite：归因追踪 ──
  memoryIds?: string[]  // 构成该 augment 的源记忆 memoryId 列表
  provenance?: 'memory' | 'fact' | 'proactive' | 'core' | 'episode' | 'other'
}

export interface BodyParams {
  maxTokensMultiplier: number
  soulTone: string
  shouldSelfCheck: boolean
  responseStyle: string
}

// ═══════════════════════════════════════════════════════════════════════════════
// MULTI-INSTANCE / SYNC
// ═══════════════════════════════════════════════════════════════════════════════

export interface SoulInstance {
  instanceId: string          // unique ID for this cc-soul instance
  name: string                // human-readable name ("cc-mac", "cc-vps", "cc-telegram")
  personality?: string        // per-instance personality override
  channels: string[]          // which channels this instance serves
  createdAt: number
}

export interface SyncConfig {
  enabled: boolean
  instanceId: string
  instanceName: string
  method: 'file' | 'http'           // file = JSONL export/import, http = API sync
  remote?: string                    // rsync target or HTTP endpoint
  syncIntervalMinutes: number        // auto-sync interval (0 = manual only)
  lastSync: number
}

export interface SyncPacket {
  fromInstance: string
  timestamp: number
  type: 'memory' | 'rule' | 'entity' | 'epistemic' | 'skill' | 'lorebook'
  payload: any
  version: number
}

export interface FederationMemory {
  content: string
  scope: string
  tags?: string[]
  sourceInstance: string
  sourceQuality: number          // source instance's avg quality score
  timestamp: number
  contentHash: string            // for dedup
}
