/**
 * Project Tools - Read-only project metadata
 *
 * Implements T-209: project.rules, project.context read
 *
 * @module packages/runtime/src/tools/project
 */

import { readFileSync, existsSync } from 'fs'
import { join } from 'path'
import type { ToolDefinition, ToolCall, ToolResultEnvelope, ISOTimeString } from '@aircoding/contracts'

export const project_rules: ToolDefinition = {
  name: 'project.rules',
  category: 'project',
  description: 'Read project rules from .air/ directory',
  input_schema: {
    type: 'object',
    properties: {
      path: { type: 'string', description: 'Relative path within .air/' }
    },
    required: ['path']
  },
  permissions: { read: true, write: false, network: false },
  streaming: false
}

export const project_context: ToolDefinition = {
  name: 'project.context',
  category: 'project',
  description: 'Read project context (ID, root, config)',
  input_schema: {
    type: 'object',
    properties: {}
  },
  permissions: { read: true, write: false, network: false },
  streaming: false
}

export function createProjectExecutor(project_root: string) {
  const resolve_air_path = (relative: string): string => {
    return join(project_root, '.air', relative)
  }

  return {
    'project.rules': async (call: ToolCall): Promise<ToolResultEnvelope> => {
      const { path } = call.arguments as { path: string }
      const full_path = resolve_air_path(path)

      if (!existsSync(full_path)) {
        return create_result(call.id, 'project.rules', 'error', { message: `Rules file not found: ${path}` })
      }

      try {
        const content = readFileSync(full_path, 'utf-8')
        return create_result(call.id, 'project.rules', 'text', { path, content })
      } catch (error) {
        return create_result(call.id, 'project.rules', 'error', { message: error instanceof Error ? error.message : String(error) })
      }
    },

    'project.context': async (call: ToolCall): Promise<ToolResultEnvelope> => {
      const project_json = join(project_root, '.air', 'shared', 'project.json')

      if (!existsSync(project_json)) {
        return create_result(call.id, 'project.context', 'error', { message: 'Project not initialized' })
      }

      try {
        const content = readFileSync(project_json, 'utf-8')
        const context = JSON.parse(content)
        return create_result(call.id, 'project.context', 'text', { project_id: context.project_id, project_root, name: context.name })
      } catch (error) {
        return create_result(call.id, 'project.context', 'error', { message: error instanceof Error ? error.message : String(error) })
      }
    }
  }
}