/**
 * Automatic Memory Lifecycle Maintenance
 *
 * Runs at session end to enforce decay/archival rules:
 * - Archive entities with confidence < 0.3
 * - Delete stale drafts (>30 days old with low decay score)
 * - Auto-promote eligible entities (draft→episode, episode→reference)
 *
 * All operations are non-fatal — failures are logged but never block session end.
 */

import { evaluateLifecycle } from "@harmony/memory";
import type { HarmonyApiClient } from "./api-client.js";

interface MemoryEntity {
  id: string;
  title: string;
  memory_tier: "draft" | "episode" | "reference";
  confidence: number;
  access_count: number;
  last_accessed_at: string | null;
  created_at: string;
}

export interface MaintenanceResult {
  archived: number;
  pruned: number;
  promoted: number;
  reviewed: number;
  errors: number;
}

/**
 * Run lifecycle maintenance for a workspace.
 * Called automatically at session end alongside consolidation.
 */
export async function runLifecycleMaintenance(
  client: HarmonyApiClient,
  workspaceId: string,
  projectId?: string,
): Promise<MaintenanceResult> {
  const result: MaintenanceResult = {
    archived: 0,
    pruned: 0,
    promoted: 0,
    reviewed: 0,
    errors: 0,
  };

  let entities: MemoryEntity[];
  try {
    const listResult = await client.listMemoryEntities({
      workspace_id: workspaceId,
      project_id: projectId,
      limit: 200,
    });
    entities = (listResult.entities || []) as MemoryEntity[];
  } catch {
    return result;
  }

  if (entities.length === 0) return result;

  const now = Date.now();
  const STALE_DRAFT_MAX_AGE_DAYS = 30;

  for (const entity of entities) {
    try {
      const lifecycle = evaluateLifecycle(entity);

      // 1. Archive low-confidence entities (confidence < 0.3)
      if (lifecycle.shouldArchive) {
        await client.deleteMemoryEntity(entity.id);
        result.archived++;
        continue;
      }

      // 2. Prune stale drafts (>30 days old with low decay score)
      if (entity.memory_tier === "draft") {
        const ageDays =
          (now - new Date(entity.created_at).getTime()) / (1000 * 60 * 60 * 24);
        if (ageDays > STALE_DRAFT_MAX_AGE_DAYS && lifecycle.decay.score < 0.3) {
          await client.deleteMemoryEntity(entity.id);
          result.pruned++;
          continue;
        }
      }

      // 3. Auto-promote eligible entities
      if (lifecycle.promotion.eligible && lifecycle.promotion.targetTier) {
        await client.updateMemoryEntity(entity.id, {
          memory_tier: lifecycle.promotion.targetTier,
          metadata: {
            promoted_at: new Date().toISOString(),
            promotion_reason: lifecycle.promotion.reason,
            promoted_from: entity.memory_tier,
          },
        });
        result.promoted++;
        continue;
      }

      // 4. Flag stale entities for review (>90 days, <3 accesses)
      if (lifecycle.shouldFlagForReview) {
        await client.updateMemoryEntity(entity.id, {
          metadata: {
            needs_review: true,
            review_reason: lifecycle.reviewReason,
            flagged_at: new Date().toISOString(),
          },
        });
        result.reviewed++;
      }
    } catch {
      result.errors++;
    }
  }

  return result;
}
