/**
 * AI Context Manager
 * Handles loading, saving, and clearing AI context files
 */

import { existsSync, readFileSync, writeFileSync, mkdirSync, unlinkSync } from 'fs'
import { join } from 'path'

/** AI context file name */
export const AI_CONTEXT_FILE = 'ai-context.md'

/** Directory for oculum files */
export const OCULUM_DIR = '.oculum'

/** Full path to AI context file (relative to project root) */
export const AI_CONTEXT_PATH = `${OCULUM_DIR}/${AI_CONTEXT_FILE}`

export interface AIContextManagerOptions {
  /** Project root path */
  projectPath: string
}

export interface SaveContextResult {
  /** Whether the save was successful */
  success: boolean
  /** Path where context was saved */
  path: string
  /** Error message (if failed) */
  error?: string
}

export interface LoadContextResult {
  /** Whether a context file was found */
  found: boolean
  /** The context content (if found) */
  content?: string
  /** Error message (if failed to load) */
  error?: string
}

export interface ClearContextResult {
  /** Whether the clear was successful */
  success: boolean
  /** Whether a context file existed before clearing */
  existed: boolean
  /** Error message (if failed) */
  error?: string
}

/**
 * Manages AI context files for IDE consumption
 */
export class AIContextManager {
  private projectPath: string
  private contextPath: string

  constructor(options: AIContextManagerOptions | string) {
    // Support both old string arg and new options object
    if (typeof options === 'string') {
      this.projectPath = options
    } else {
      this.projectPath = options.projectPath
    }
    this.contextPath = join(this.projectPath, OCULUM_DIR, AI_CONTEXT_FILE)
  }

  /**
   * Get the full path to the AI context file
   */
  getContextPath(): string {
    return this.contextPath
  }

  /**
   * Save AI context to .oculum/ai-context.md
   */
  saveContext(content: string): SaveContextResult {
    try {
      // Ensure .oculum directory exists
      const oculumDir = join(this.projectPath, OCULUM_DIR)
      if (!existsSync(oculumDir)) {
        mkdirSync(oculumDir, { recursive: true })
      }

      // Write content to file
      writeFileSync(this.contextPath, content)

      return { success: true, path: this.contextPath }
    } catch (err) {
      return {
        success: false,
        path: this.contextPath,
        error: `Failed to save AI context: ${err instanceof Error ? err.message : 'Unknown error'}`,
      }
    }
  }

  /**
   * Load AI context from .oculum/ai-context.md
   */
  loadContext(): LoadContextResult {
    if (!existsSync(this.contextPath)) {
      return { found: false }
    }

    try {
      const content = readFileSync(this.contextPath, 'utf-8')
      return { found: true, content }
    } catch (err) {
      return {
        found: false,
        error: `Failed to read AI context: ${err instanceof Error ? err.message : 'Unknown error'}`,
      }
    }
  }

  /**
   * Clear (delete) the AI context file
   */
  clearContext(): ClearContextResult {
    const existed = existsSync(this.contextPath)

    if (!existed) {
      return { success: true, existed: false }
    }

    try {
      unlinkSync(this.contextPath)
      return { success: true, existed: true }
    } catch (err) {
      return {
        success: false,
        existed: true,
        error: `Failed to clear AI context: ${err instanceof Error ? err.message : 'Unknown error'}`,
      }
    }
  }

  /**
   * Check if an AI context file exists
   */
  hasContext(): boolean {
    return existsSync(this.contextPath)
  }
}
