import { writeFile, readFile, mkdir } from "node:fs/promises";
import { join, basename } from "node:path";
import { homedir } from "node:os";
import type { ChatMessage, Conversation } from "./types.js";

const AGENT_NAME = basename(process.cwd()).replace(/-channel$/, "");
const PERSIST_DIR = join(homedir(), ".claude", "channels", AGENT_NAME);
const PERSIST_FILE = join(PERSIST_DIR, "conversations.json");
const DEBOUNCE_MS = 2000;

export class ConversationStore {
  private conversations = new Map<string, Conversation>();
  private persistTimer: ReturnType<typeof setTimeout> | null = null;

  async load(): Promise<void> {
    try {
      const data = await readFile(PERSIST_FILE, "utf-8");
      const parsed: Record<string, Conversation> = JSON.parse(data);
      for (const [id, conv] of Object.entries(parsed)) {
        this.conversations.set(id, conv);
      }
    } catch {
      // No existing data or parse error — start fresh
    }
  }

  get(conversationId: string): Conversation | undefined {
    return this.conversations.get(conversationId);
  }

  list(): Conversation[] {
    return Array.from(this.conversations.values()).sort(
      (a, b) => b.updated_at - a.updated_at
    );
  }

  addMessage(conversationId: string, message: ChatMessage): void {
    let conv = this.conversations.get(conversationId);
    if (!conv) {
      conv = {
        id: conversationId,
        messages: [],
        created_at: Date.now(),
        updated_at: Date.now(),
      };
      this.conversations.set(conversationId, conv);
    }
    conv.messages.push(message);
    conv.updated_at = Date.now();
    this.schedulePersist();
  }

  private schedulePersist(): void {
    if (this.persistTimer) clearTimeout(this.persistTimer);
    this.persistTimer = setTimeout(() => this.persist(), DEBOUNCE_MS);
  }

  private async persist(): Promise<void> {
    try {
      await mkdir(PERSIST_DIR, { recursive: true });
      const data: Record<string, Conversation> = {};
      for (const [id, conv] of this.conversations) {
        data[id] = conv;
      }
      await writeFile(PERSIST_FILE, JSON.stringify(data, null, 2));
    } catch (err) {
      process.stderr.write(`[${AGENT_NAME}-channel] persist error: ${err}\n`);
    }
  }
}
