import { Injectable } from '@nestjs/common';
import { StorageService } from '../storage/storage.service';
import type { AgentTool, ToolDescriptor, ToolInvocation, ToolResult } from './tool.types';

/**
 * PR10.5 `file_save` tool —— 把内容存到 StorageBackend。
 *
 * 走三层 scope 解析（PROJECT > USER > ORGANIZATION），自动落 LOCAL 默认 binding。
 * 后续上 OneDrive binding 后无缝切换 backend。
 */
@Injectable()
export class FileSaveTool implements AgentTool {
  constructor(private readonly storage: StorageService) {}

  readonly descriptor: ToolDescriptor = {
    name: 'file_save',
    description:
      '把 agent 产出的文本内容保存到用户/项目/组织的存储后端（自动 LOCAL 兜底，配 OneDrive 后切到 OneDrive）。',
    inputSchema: {
      path: { type: 'string', required: true, description: '相对路径，例如 reports/2026-05/summary.md' },
      content: { type: 'string', required: true, description: '文本内容' },
      mimeType: { type: 'string', required: false, description: 'mime type，默认 text/plain' },
    },
    availability: { surface: ['web', 'desktop', 'mobile', 'teams', 'cli'] },
    writeAction: true,
  };

  async invoke(inv: ToolInvocation): Promise<ToolResult> {
    const p = String(inv.input.path ?? '').trim();
    const content = String(inv.input.content ?? '');
    if (!p || !content) return { ok: false, errorMessage: 'path 和 content 必填' };
    try {
      const r = await this.storage.upload({
        organizationId: inv.organizationId,
        userId: inv.userId,
        path: p,
        content: Buffer.from(content, 'utf8'),
        mimeType: String(inv.input.mimeType ?? 'text/plain'),
      });
      return {
        ok: true,
        output: { fileId: r.fileId, sizeBytes: r.sizeBytes, sha256: r.sha256.slice(0, 16) },
      };
    } catch (err) {
      return { ok: false, errorMessage: (err as Error).message };
    }
  }
}
