/**
 * TODO Store — JSON file-based persistence.
 *
 * Responsibilities:
 *   - Load/save todos from/to a JSON file
 *   - CRUD operations (create, read, update, delete)
 *   - Atomic file writes (write to temp, rename)
 *   - Auto-create storage directory on first use
 *
 * Storage path: TODO_FILE env var or ~/.todo-app/todos.json
 *
 * @see spec.md for full requirements
 */
import { Todo, TodoCreateInput, TodoUpdateInput, TodoStats, Priority } from './types.js';

// TODO: Implement TodoStore class
// This file will be completed by an AI tool via proxym ticket dispatch.

export class TodoStore {
  private todos: Todo[] = [];
  private filePath: string;

  constructor(filePath?: string) {
    this.filePath = filePath || process.env.TODO_FILE || `${process.env.HOME || '.'}/.todo-app/todos.json`;
  }

  async load(): Promise<void> {
    try {
      const fs = await import('fs/promises');
      const data = await fs.readFile(this.filePath, 'utf-8');
      this.todos = JSON.parse(data);
    } catch { this.todos = []; }
  }

  async save(): Promise<void> {
    const fs = await import('fs/promises');
    const path = await import('path');
    await fs.mkdir(path.dirname(this.filePath), { recursive: true });
    await fs.writeFile(this.filePath, JSON.stringify(this.todos, null, 2));
  }

  create(input: TodoCreateInput): Todo {
    const todo: Todo = {
      id: Math.random().toString(36).slice(2, 10) + Date.now().toString(36),
      title: input.title,
      description: input.description || '',
      priority: input.priority || 'medium',
      done: false,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    this.todos.push(todo);
    return todo;
  }

  list(): Todo[] { return [...this.todos]; }

  get(id: string): Todo | undefined { return this.todos.find(t => t.id === id); }

  update(id: string, input: TodoUpdateInput): Todo | undefined {
    const todo = this.todos.find(t => t.id === id);
    if (!todo) return undefined;
    if (input.title !== undefined) todo.title = input.title;
    if (input.description !== undefined) todo.description = input.description;
    if (input.priority !== undefined) todo.priority = input.priority;
    if (input.done !== undefined) todo.done = input.done;
    todo.updatedAt = new Date().toISOString();
    return todo;
  }

  delete(id: string): boolean {
    const idx = this.todos.findIndex(t => t.id === id);
    if (idx === -1) return false;
    this.todos.splice(idx, 1);
    return true;
  }

  stats(): TodoStats {
    const total = this.todos.length;
    const done = this.todos.filter(t => t.done).length;
    const byPriority = { low: 0, medium: 0, high: 0 };
    for (const t of this.todos) byPriority[t.priority]++;
    return { total, done, pending: total - done, byPriority };
  }
}
