import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { z } from 'zod';

import type { AppConfig } from '../config.js';
import { audit } from '../audit/logger.js';
import { getContext, newRequestId, type RequestContext } from '../auth/context.js';
import {
  assertClassFilterAllowed,
  assertInScope,
  assertSelf,
  assertStatus,
  requireCounselor,
  requireStudent,
} from '../auth/authorize.js';
import { conflict, forbidden, identityRequired, invalidArgument, normalizeError } from '../errors/index.js';
import { newAuditRecord, type AuditSink } from '../audit/store.js';
import {
  anomalyQueryShape,
  checkOutShape,
  createLeaveShape,
  listQueryShape,
  requestIdShape,
  reviewShape,
  summaryQueryShape,
  toLeaveView,
  withdrawShape,
  LEAVE_CATEGORY_LABEL,
  LeaveCategorySchema,
  LeaveTypeSchema,
  type AttachmentRef,
  type LeaveCategory,
  type LeaveType,
} from '../schemas/attendance.js';
import { scopeOf } from '../auth/types.js';
import type { HaisoftClient } from '../adapters/types.js';
import { CasClient } from '../adapters/cas-client.js';
import { IdempotencyStore, deriveIdempotencyKey } from '../utils/idempotency.js';
import { parseLeaveText } from '../leaves/parser.js';
import { evaluateDraft, type LeaveDraft } from '../leaves/draft.js';
import {
  IDENTITY_REQUIRED_MESSAGE,
  identityRequiredDetails,
} from '../profile/identity.js';
import type { ProfileStore } from '../profile/store.js';
import { publicView, type IdentityRole } from '../profile/types.js';

export type ContextResolver = () => Promise<RequestContext>;

export interface ServerDeps {
  config: AppConfig;
  client: HaisoftClient;
  idempotency?: IdempotencyStore;
  /** 本地身份档案。提供后才启用 select_identity / get_identity_status */
  profileStore?: ProfileStore;
  /** 身份解析入口。默认读请求作用域上下文；profile 模式由入口注入档案解析器 */
  resolveContext?: ContextResolver;
  /** 审计持久化（60 天），可选 */
  auditSink?: AuditSink;
  /** 保存身份后立即验证凭据是否可用（用当前活动档案登录一次） */
  verifyLogin?: () => Promise<void>;
}

const READ_ONLY = { readOnlyHint: true, openWorldHint: true } as const;
const WRITE = { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true } as const;

function text(payload: unknown): CallToolResult {
  return {
    content: [
      {
        type: 'text',
        text: typeof payload === 'string' ? payload : JSON.stringify(payload, null, 2),
      },
    ],
  };
}


/* ============================ 请假引导流程的公共定义 ============================ */

const isoDateTimeSchema = z
  .string()
  .datetime({ offset: true, message: '时间必须是带 +08:00 时区的 ISO 8601，例如 2026-10-29T08:00:00+08:00' });

const attachmentShape = {
  name: z.string().min(1).max(200).describe('文件名，例如 校医院病历.jpg'),
  mimeType: z.string().max(100).optional().describe('MIME 类型'),
  sizeBytes: z.number().int().min(0).optional().describe('文件大小（字节），单个上限 10 MB'),
  url: z.string().max(2000).optional().describe('客户端可访问的地址；服务端只登记，不下载内容'),
};

const draftShape = {
  text: z
    .string()
    .max(2000)
    .optional()
    .describe('用户原话，原样传入。服务端会解析时间段、事由与请假类型作为兜底'),
  category: LeaveCategorySchema.optional().describe('routine 普通请假 / offcampus 离校请假'),
  leaveType: LeaveTypeSchema.optional().describe('sick 病假 / personal 事假 / official 公假 / other 其他'),
  startAt: isoDateTimeSchema.optional().describe('请假开始时间'),
  endAt: isoDateTimeSchema.optional().describe('请假结束时间'),
  reason: z.string().max(500).optional().describe('请假事由，至少 5 个字'),
  destination: z.string().max(100).optional().describe('离校去向，离校请假必填'),
  guardianContact: z.string().max(20).optional().describe('家长或本人联系电话，离校请假必填'),
  attachments: z.array(z.object(attachmentShape)).max(5).optional().describe('附件列表，最多 5 个'),
};

interface DraftBuildResult {
  draft: LeaveDraft;
  parsed: {
    confidence: string;
    notes: string[];
    inferred: string[];
  };
}

/**
 * 合并「用户原话解析」与「模型显式传入的字段」。
 * 显式字段优先：模型语义分析的准确度高于正则，正则只是兜底。
 */
function buildDraft(args: {
  text?: string | undefined;
  category?: LeaveCategory | undefined;
  leaveType?: LeaveType | undefined;
  startAt?: string | undefined;
  endAt?: string | undefined;
  reason?: string | undefined;
  destination?: string | undefined;
  guardianContact?: string | undefined;
  attachments?: AttachmentRef[] | undefined;
}, now: Date = new Date()): DraftBuildResult {
  const parsed = args.text ? parseLeaveText(args.text, now) : undefined;
  const inferred: string[] = [];
  if (!args.category && parsed?.category) inferred.push('category');
  if (!args.leaveType && parsed?.leaveType) inferred.push('leaveType');
  if (!args.startAt && parsed?.window.startAt) inferred.push('startAt');
  if (!args.endAt && parsed?.window.endAt) inferred.push('endAt');
  if (!args.reason && parsed?.reason) inferred.push('reason');

  return {
    draft: {
      ...(args.category ?? parsed?.category ? { category: args.category ?? parsed?.category } : {}),
      ...(args.leaveType ?? parsed?.leaveType ? { leaveType: args.leaveType ?? parsed?.leaveType } : {}),
      ...(args.startAt ?? parsed?.window.startAt ? { startAt: args.startAt ?? parsed?.window.startAt } : {}),
      ...(args.endAt ?? parsed?.window.endAt ? { endAt: args.endAt ?? parsed?.window.endAt } : {}),
      ...(args.reason ?? parsed?.reason ? { reason: args.reason ?? parsed?.reason } : {}),
      ...(args.destination ? { destination: args.destination } : {}),
      ...(args.guardianContact ? { guardianContact: args.guardianContact } : {}),
      attachments: args.attachments ?? [],
    },
    parsed: {
      confidence: parsed?.window.confidence ?? 'none',
      notes: parsed?.window.notes ?? [],
      inferred,
    },
  };
}

export function createServer(deps: ServerDeps): McpServer {
  const { config, client } = deps;
  const idempotency = deps.idempotency ?? new IdempotencyStore({ ttlMs: config.idempotencyTtlMs });
  const store = deps.profileStore;
  /**
   * 写操作可见性：显式开关，或上游是 mock（此时不存在真实写入，放开才能体验完整流程）。
   * 接真实后台（HAISOFT_API_MODE=http）时只认 ENABLE_WRITE_TOOLS。
   */
  const writesEnabled = config.enableWriteTools;
  const resolveContext: ContextResolver = deps.resolveContext ?? (async () => getContext());

  const server = new McpServer(
    { name: config.serverName, version: config.serverVersion },
    {
      instructions:
        '海软假勤管家。首次使用必须先调用 get_identity_status 检查身份，再用 select_identity 让用户选择「学生」或「辅导员」，' +
        '选择结果保存到本地配置，之后直接沿用。' +
        '所有数据范围由服务端根据已选身份推导，不要尝试通过参数指定其他学生、班级或管理范围。' +
        '写操作会进入审计记录；提交前必须向用户复述关键信息并取得确认。' +
        (config.endpoint.mode === 'public'
          ? '当前是无令牌公开端点：只读，且不接收任何账号凭据。要提交请假或审批，请用户在本机运行本地版 MCP。'
          : ''),
    },
  );

  /** 审计落盘：失败不影响主流程 */
  async function persist(record: Parameters<typeof newAuditRecord>[0]): Promise<void> {
    if (!deps.auditSink) {
      return;
    }
    try {
      await deps.auditSink.append(newAuditRecord(record));
    } catch {
      // 审计失败不能阻断业务调用
    }
  }

  /** 统一执行壳：身份、审计、错误归一化、结果序列化 */
  async function run<T>(
    meta: { tool: string; write?: boolean; args?: unknown; targetIds?: string[] },
    fn: (ctx: RequestContext) => Promise<T>,
  ): Promise<CallToolResult> {
    const started = Date.now();
    let ctx: RequestContext | undefined;
    try {
      ctx = await resolveContext();
      const data = await fn(ctx);
      const durationMs = Date.now() - started;
      audit({
        requestId: ctx.requestId,
        userId: ctx.user.userId,
        roles: ctx.user.roles,
        tool: meta.tool,
        write: meta.write ?? false,
        outcome: 'ok',
        durationMs,
        ...(meta.targetIds ? { targetIds: meta.targetIds } : {}),
        ...(meta.args !== undefined ? { args: meta.args } : {}),
        logArgs: config.audit.logArgs,
      });
      await persist({
        requestId: ctx.requestId,
        userId: ctx.user.userId,
        roles: ctx.user.roles,
        tool: meta.tool,
        write: meta.write ?? false,
        outcome: 'ok',
        durationMs,
        ...(meta.targetIds ? { targetIds: meta.targetIds } : {}),
        ...(config.audit.logArgs && meta.args !== undefined ? { args: meta.args } : {}),
      });
      return text({ ok: true, tool: meta.tool, data });
    } catch (error) {
      const normalized = normalizeError(error);
      const durationMs = Date.now() - started;
      audit({
        requestId: ctx?.requestId ?? 'unauthenticated',
        userId: ctx?.user.userId ?? 'anonymous',
        roles: ctx?.user.roles ?? [],
        tool: meta.tool,
        write: meta.write ?? false,
        outcome: 'error',
        errorCode: normalized.code,
        durationMs,
        ...(meta.args !== undefined ? { args: meta.args } : {}),
        logArgs: config.audit.logArgs,
      });
      await persist({
        requestId: ctx?.requestId ?? 'unauthenticated',
        userId: ctx?.user.userId ?? 'anonymous',
        roles: ctx?.user.roles ?? [],
        tool: meta.tool,
        write: meta.write ?? false,
        outcome: 'error',
        errorCode: normalized.code,
        durationMs,
        ...(config.audit.logArgs && meta.args !== undefined ? { args: meta.args } : {}),
      });
      return { isError: true, ...text(normalized.toResult()) };
    }
  }

  /** 身份配置类工具的执行壳：不需要已选身份即可调用 */
  async function runSetup<T>(
    meta: { tool: string; write?: boolean; args?: unknown },
    fn: () => Promise<T>,
  ): Promise<CallToolResult> {
    const started = Date.now();
    const requestId = newRequestId('setup');
    try {
      const data = await fn();
      await persist({
        requestId,
        userId: 'setup',
        roles: [],
        tool: meta.tool,
        write: meta.write ?? false,
        outcome: 'ok',
        durationMs: Date.now() - started,
      });
      return text({ ok: true, tool: meta.tool, data });
    } catch (error) {
      const normalized = normalizeError(error);
      await persist({
        requestId,
        userId: 'setup',
        roles: [],
        tool: meta.tool,
        write: meta.write ?? false,
        outcome: 'error',
        errorCode: normalized.code,
        durationMs: Date.now() - started,
      });
      return { isError: true, ...text(normalized.toResult()) };
    }
  }

  /** 写操作幂等壳 */
  async function idempotent<T>(
    ctx: RequestContext,
    tool: string,
    args: unknown,
    rawKey: string | undefined,
    fn: () => Promise<T>,
  ): Promise<{ result: T; replayed: boolean }> {
    const key = rawKey
      ? `${ctx.user.userId}:${tool}:${rawKey}`
      : deriveIdempotencyKey(ctx.user.userId, tool, args);
    const decision = idempotency.begin(key);
    if (decision.kind === 'in_flight') {
      throw conflict('同一请求正在处理中，请勿重复提交', { retryable: true });
    }
    if (decision.kind === 'replay') {
      return { result: decision.result as T, replayed: true };
    }
    try {
      const result = await fn();
      idempotency.complete(key, result);
      return { result, replayed: false };
    } catch (error) {
      idempotency.fail(key);
      throw error;
    }
  }

  /**
   * 保存身份后立刻登录一次，确认凭据真的可用。
   * 失败时把刚写入的密码清掉，避免用户以为已保存、实际每次登录都失败。
   */
  async function verifyIfRequested(profileId: string, enabled: boolean, passwordSaved: boolean): Promise<boolean> {
    if (!enabled || !deps.verifyLogin) {
      return false;
    }
    try {
      await deps.verifyLogin();
      return true;
    } catch (error) {
      if (passwordSaved) {
        await profileOp(() => store?.clearSecret(profileId) ?? Promise.resolve());
      }
      throw invalidArgument(
        `凭据验证失败：${error instanceof Error ? error.message : String(error)}`,
        { profileId, passwordStored: false, hint: '请核对后重新输入，或传 verifyLogin=false 跳过验证' },
      );
    }
  }

  /** 身份档案读写包装：把存储层错误转成用户可读、可操作的提示 */
  async function profileOp<T>(fn: () => Promise<T>): Promise<T> {
    try {
      return await fn();
    } catch (error) {
      throw invalidArgument(`身份档案操作失败：${error instanceof Error ? error.message : String(error)}`);
    }
  }

  /* ============================ 身份选择（首次必做） ============================ */

  /** CAS 登录：每次新建客户端，避免不同用户的 Cookie 罐互相污染 */
  function requireCas(): CasClient {
    if (!config.cas.enabled) {
      throw invalidArgument('CAS 校园网登录已关闭（ENABLE_CAS_LOGIN=false）');
    }
    return new CasClient({
      authBase: config.cas.authBase,
      ehallBase: config.cas.ehallBase,
      service: config.cas.service,
      tlsMode: config.cas.tlsMode,
      timeoutMs: config.cas.timeoutMs,
    });
  }

  /**
   * 公开端点（无令牌）不得接收凭据。
   *
   * 一旦允许，云端档案就会保存别人的学号密码，且所有人共用这一个身份，
   * 等于把账号交给任何拿到 URL 的人。「凭据只在本地存储」必须由代码保证，而不是靠约定。
   */
  function assertCredentialLocalOnly(): void {
    if (config.endpoint.mode === 'public') {
      throw forbidden(
        '该端点是无令牌的公开端点，不接收任何账号凭据。' +
          '请在本机安装并使用本地版 MCP（stdio）后再选择身份，凭据只保存在你本机的档案文件里。',
      );
    }
  }

  server.registerTool(
    'login_with_cas',
    {
      title: 'CAS 校园网认证登录（学生）',
      description:
        '学生用统一身份认证（CAS）登录，成功后自动从一站式大厅读取学号、姓名、班级、学院并保存到本地档案，' +
        '不需要手工填四项。密码只用于登录，默认不落盘。' +
        '注意：CAS 首次登录若命中「单处登录」会自动踢掉该账号在其他设备上的会话。' +
        '若返回 CAPTCHA_REQUIRED（要求图形验证码），改用 select_identity 手动填写四项。',
      inputSchema: {
        studentNum: z.string().min(4).max(32).describe('学号'),
        password: z.string().min(4).max(128).describe('统一身份认证密码'),
        savePassword: z
          .boolean()
          .default(false)
          .describe('是否把 CAS 密码保存到本地（0600）。默认不保存，仅本次登录使用'),
      },
      annotations: { ...WRITE, destructiveHint: false },
    },
    (args) =>
      runSetup({ tool: 'login_with_cas', write: true, args: { studentNum: args.studentNum, password: '***' } }, async () => {
        assertCredentialLocalOnly();
        if (!store) {
          throw invalidArgument('当前运行模式未启用本地身份档案，无法保存身份');
        }
        const cas = requireCas();
        const info = await cas.login(args.studentNum, args.password);

        const profile = await profileOp(() =>
          store.upsertStudent({
            studentNum: info.studentNum,
            name: info.name,
            className: info.className,
            college: info.college,
            source: 'cas',
            ...(info.classCode ? { classCode: info.classCode } : {}),
            ...(info.grade ? { grade: info.grade } : {}),
            ...(info.categoryName ? { categoryName: info.categoryName } : {}),
            ...(info.personWid ? { personWid: info.personWid } : {}),
          }),
        );
        if (args.savePassword) {
          await profileOp(() => store.setSecret(profile.id, args.password));
        }

        return {
          saved: true,
          source: 'cas',
          profile: publicView(profile),
          configPath: store.location,
          passwordStored: args.savePassword,
          canCallTools: true,
          note: '已从一站式大厅读取到学号、姓名、班级、学院，可直接调用业务工具',
        };
      }),
  );

  server.registerTool(
    'get_identity_status',
    {
      title: '检查身份状态',
      description:
        '查询本地是否已保存身份、当前正在使用哪个身份，以及可切换的档案列表。' +
        '首次使用或不确定当前身份时，先调用本工具。',
      inputSchema: {},
      annotations: READ_ONLY,
    },
    () =>
      runSetup({ tool: 'get_identity_status' }, async () => {
        if (!store) {
          return {
            configured: false,
            profileStoreEnabled: false,
            note: '当前运行模式未启用本地身份档案（使用 token 或 static 鉴权）',
          };
        }
        const active = await profileOp(() => store.getActive());
        const available = await profileOp(() => store.list());
        const passwordStored =
          active && active.role === 'counselor' ? await profileOp(() => store.hasSecret(active.id)) : undefined;
        return {
          configured: Boolean(active),
          profileStoreEnabled: true,
          active: active ? publicView(active) : null,
          available: available.map(publicView),
          configPath: store.location,
          nextStep: active ? '身份已就绪，可直接调用业务工具' : IDENTITY_REQUIRED_MESSAGE,
          ...(passwordStored === undefined ? {} : { passwordStored }),
        };
      }),
  );

  server.registerTool(
    'select_identity',
    {
      title: '选择身份',
      description:
        '让用户选择「学生」或「辅导员」身份，并把该身份保存到本地配置文件。' +
        '学生需要学号、姓名、班级、学院四项（学生登录正是校验这四项，不需要密码）；' +
        '辅导员需要工号，密码由用户提供，默认保存到本地 0600 权限文件。' +
        '已保存过身份时传 profileId 即可切换。',
      inputSchema: {
        role: z.enum(['student', 'counselor']).optional().describe('身份类型：student 学生 / counselor 辅导员'),
        profileId: z
          .string()
          .max(64)
          .optional()
          .describe('已保存档案的 id（形如 student:20250000001），用于切换身份'),
        studentNum: z.string().min(4).max(32).optional().describe('学号，学生必填'),
        name: z.string().min(2).max(32).optional().describe('姓名，学生必填'),
        className: z.string().min(2).max(64).optional().describe('班级，学生必填，例如 25软件技术001'),
        college: z.string().min(2).max(64).optional().describe('学院，学生必填，例如 计算机与人工智能学院'),
        jobNum: z.string().min(2).max(32).optional().describe('工号，辅导员必填'),
        password: z.string().min(4).max(128).optional().describe('辅导员登录密码'),
        savePassword: z
          .boolean()
          .default(true)
          .describe('是否把密码保存到本地配置文件（0600 权限）。用户不希望落盘时传 false'),
        verifyLogin: z
          .boolean()
          .default(true)
          .describe('保存后是否立即登录一次验证凭据。失败会报错并清除刚存的密码'),
        manageableClassIds: z
          .array(z.string().max(64))
          .optional()
          .describe('辅导员的授权管理班级。留空表示尚未获得授权范围，此时辅导员工具查不到数据'),
      },
      annotations: { ...WRITE, destructiveHint: false },
    },
    (args) =>
      runSetup({ tool: 'select_identity', write: true, args: { ...args, password: args.password ? '***' : undefined } }, async () => {
        assertCredentialLocalOnly();
        if (!store) {
          throw invalidArgument('当前运行模式未启用本地身份档案，无法保存身份');
        }

        if (args.profileId) {
          const available = await profileOp(() => store.list().then((list) => list.map((p) => p.id)));
          const target = await profileOp(() => store.setActive(args.profileId as string));
          if (!target) {
            throw invalidArgument(`未找到已保存的身份档案 ${args.profileId}`, { available });
          }
          const passwordStored =
            target.role === 'counselor' ? await profileOp(() => store.hasSecret(target.id)) : false;
          return {
            switched: true,
            profile: publicView(target),
            configPath: store.location,
            ...(target.role === 'counselor'
              ? { passwordStored, needsPassword: !passwordStored }
              : {}),
          };
        }

        if (!args.role) {
          throw identityRequired(IDENTITY_REQUIRED_MESSAGE, identityRequiredDetails());
        }

        const role: IdentityRole = args.role;

        if (role === 'student') {
          const missing: string[] = [];
          if (!args.studentNum) missing.push('studentNum 学号');
          if (!args.name) missing.push('name 姓名');
          if (!args.className) missing.push('className 班级');
          if (!args.college) missing.push('college 学院');
          if (missing.length > 0) {
            throw invalidArgument('学生还缺少必填信息，请向用户确认后再调用', {
              missing,
              example: {
                role: 'student',
                studentNum: '20250000001',
                name: '张三',
                className: '25软件技术001',
                college: '计算机与人工智能学院',
              },
            });
          }
          const profile = await profileOp(() =>
            store.upsertStudent({
              studentNum: args.studentNum as string,
              name: args.name as string,
              className: args.className as string,
              college: args.college as string,
            }),
          );
          const loginVerified = await verifyIfRequested(profile.id, args.verifyLogin !== false, false);
          return {
            saved: true,
            profile: publicView(profile),
            configPath: store.location,
            canCallTools: true,
            loginVerified,
          };
        }

        if (!args.jobNum) {
          throw invalidArgument('辅导员需要提供工号（jobNum）', {
            example: { role: 'counselor', jobNum: '10001', password: '<用户输入的密码>' },
          });
        }
        const profile = await profileOp(() =>
          store.upsertCounselor({
            jobNum: args.jobNum as string,
            ...(args.name ? { name: args.name } : {}),
            ...(args.manageableClassIds ? { manageableClassIds: args.manageableClassIds } : {}),
          }),
        );
        if (args.password && args.savePassword !== false) {
          await profileOp(() => store.setSecret(profile.id, args.password as string));
        }
        const passwordStored = await profileOp(() => store.hasSecret(profile.id));
        const loginVerified = await verifyIfRequested(profile.id, args.verifyLogin !== false, passwordStored);
        return {
          saved: true,
          profile: publicView(profile),
          configPath: store.location,
          passwordStored,
          loginVerified,
          ...(passwordStored
            ? {}
            : {
                needsPassword: true,
                prompt: '辅导员登录需要密码，请向用户索取后再次调用 select_identity 并传入 password',
              }),
        };
      }),
  );

  /* ============================ 只读工具（阶段 1） ============================ */


  server.registerTool(
    'get_current_user',
    {
      title: '获取当前用户身份',
      description:
        '返回当前已认证用户的身份与角色，以及其被授权的管理范围。' +
        '用于确认「我是谁、我能做什么」，不返回身份证、手机号等敏感字段。',
      inputSchema: {},
      annotations: READ_ONLY,
    },
    () =>
      run({ tool: 'get_current_user' }, async (ctx) => ({
        userId: ctx.user.userId,
        name: ctx.user.name,
        roles: ctx.user.roles,
        classIds: ctx.user.classIds,
        manageableClassIds: ctx.user.manageableClassIds,
        ...(ctx.user.departmentId ? { departmentId: ctx.user.departmentId } : {}),
      })),
  );





  server.registerTool(
    'list_pending_approvals',
    {
      title: '查询待我审批的申请',
      description:
        '辅导员查询授权管理范围内的待审批请假申请，默认只返回「待批准」。' +
        '传 status=approved 或 rejected 可查已处理的历史；范围由服务端根据身份推导，' +
        '无法通过参数扩大——上游按会话只下发本人负责的学生。',
      inputSchema: listQueryShape,
      annotations: READ_ONLY,
    },
    (args) =>
      run({ tool: 'list_pending_approvals', args }, async (ctx) => {
        requireCounselor(ctx.user);
        const scope = scopeOf(ctx.user);
        // 空的本地范围不再等于「无数据」：上游按辅导员会话下发，本身已是权限边界。
        // 本地声明的范围只在非空时作为额外收紧。
        const page = await client.listPendingApprovals(scope, args);
        const localScope = scope.classIds.length > 0 || scope.studentIds.length > 0;
        return {
          items: page.items.map(toLeaveView),
          ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),
          count: page.items.length,
          scope,
          scopeSource: localScope ? 'local' : 'upstream',
          ...(localScope
            ? {}
            : { note: '未在本地声明管理范围，按上游会话可见范围返回（易班只下发本人负责的学生）' }),
        };
      }),
  );




  server.registerTool(
    'list_my_leave_requests',
    {
      title: '查询我的请假记录',
      description:
        '学生查询本人请假记录，含待批准 / 已批准 / 不批准与辅导员审批意见。' +
        '学生首页内嵌的数据只含本人记录，服务端仍按学号再过滤一次，防止上游下发范围变化导致串号。' +
        '可用于提交后确认单据是否落地、辅导员是否已处理。',
      inputSchema: listQueryShape,
      annotations: READ_ONLY,
    },
    (args) =>
      run({ tool: 'list_my_leave_requests', args }, async (ctx) => {
        requireStudent(ctx.user);
        const page = await client.listMyLeaveRequests(ctx.user.userId, args);
        return {
          items: page.items.map(toLeaveView),
          count: page.items.length,
          ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),
        };
      }),
  );

  /* ==================== 学生请假引导：选类型 → 解析预览 → 提交 ==================== */

  server.registerTool(
    'start_leave_application',
    {
      title: '发起请假（第一步：选类型）',
      description:
        '学生发起请假的第一步，只返回选项，不写任何数据。' +
        '返回「普通请假」与「离校请假」两项及各自必需字段，模型必须把 options 原样呈现给用户，不要替用户决定。' +
        '用户选定后调用 preview_leave_application。',
      inputSchema: {},
      annotations: READ_ONLY,
    },
    () =>
      run({ tool: 'start_leave_application' }, async (ctx) => {
        requireStudent(ctx.user);
        return {
          stage: 'need_category',
          question: '这次请假属于哪一类？',
          options: [
            {
              value: 'routine',
              label: LEAVE_CATEGORY_LABEL.routine,
              description: '不离开校园：校内就医、宿舍休息、学院活动等',
              extraFields: [],
            },
            {
              value: 'offcampus',
              label: LEAVE_CATEGORY_LABEL.offcampus,
              description: '离开校园：回家、外出就医、外地办事等',
              extraFields: [
                { field: 'destination', label: '离校去向', hint: '例如 海口市人民医院 / 家中（三亚）' },
                { field: 'guardianContact', label: '家长或本人联系电话', hint: '必须能接通' },
              ],
            },
          ],
          nextStep:
            '用户选定类型后调用 preview_leave_application：把用户原话放进 text，附件放进 attachments，' +
            '不要自己编造时间段或事由',
          notes: [
            '时间、事由用户没说清时，preview 会返回 missing 与 timePicker，据此前置追问',
            '单个附件上限 10 MB，最多 5 个',
          ],
        };
      }),
  );

  server.registerTool(
    'preview_leave_application',
    {
      title: '请假草稿解析与校验',
      description:
        '把用户原话、附件与已知字段交给服务端解析：自动识别请假时间段、事由、请假类型，' +
        '返回 stage（need_category/need_time/need_fields/ready）、missing（还缺什么）、' +
        'timePicker（需要用户选时间时的可选项）与 summary（一句话摘要）。' +
        '本工具不提交、不写数据。信息齐了再调 submit_leave_application。',
      inputSchema: draftShape,
      annotations: READ_ONLY,
    },
    (args) =>
      run({ tool: 'preview_leave_application', args }, async (ctx) => {
        requireStudent(ctx.user);
        const { draft, parsed } = buildDraft(args);
        const evaluation = evaluateDraft(draft, new Date());

        return {
          stage: evaluation.stage,
          summary: evaluation.summary,
          draft,
          durationDays: evaluation.durationDays,
          timeSuggestions: evaluation.timeSuggestions,
          missing: evaluation.missing,
          errors: evaluation.errors,
          warnings: evaluation.warnings,
          parsed,
          ...(evaluation.stage === 'need_time'
            ? {
                timePicker: {
                  question: '用户没有给出可用的请假时间，请让用户选择或拖动调整',
                  field: 'timeRange',
                  suggestions: evaluation.timeSuggestions,
                  format: 'ISO 8601 带 +08:00 时区，例如 2026-10-29T08:00:00+08:00',
                  hint: '用户选定或调整后，把 startAt / endAt 回传 preview 再确认一次',
                },
              }
            : {}),
          attachments: {
            received: draft.attachments.length,
            items: draft.attachments.map((a) => a.name),
            uploadSupported: false,
            note: '真实上传接口尚未确认，当前只登记文件名与大小，不搬运文件内容',
          },
          nextStep:
            evaluation.stage === 'ready'
              ? '把 summary 复述给用户并确认无误，确认后调用 submit_leave_application'
              : '把 missing / timePicker 呈现给用户补齐，补齐后再次调用 preview',
        };
      }),
  );

  server.registerTool(
    'query_my_audit_log',
    {
      title: '查询我的调用审计',
      description:
        `查询本人最近 ${config.audit.retentionDays} 天内的工具调用记录（时间、工具、结果、耗时、目标记录）。` +
        '只能看到自己的记录，userId 由服务端绑定，无法通过参数查询他人。',
      inputSchema: {
        tool: z.string().max(64).optional().describe('按工具名过滤'),
        outcome: z.enum(['ok', 'error']).optional().describe('按结果过滤'),
        from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('起始日期 YYYY-MM-DD'),
        to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('结束日期 YYYY-MM-DD'),
        limit: z.number().int().min(1).max(200).default(50),
      },
      annotations: READ_ONLY,
    },
    (args) =>
      run({ tool: 'query_my_audit_log', args }, async (ctx) => {
        if (!deps.auditSink) {
          throw invalidArgument('未启用审计持久化，当前仅输出到服务端日志');
        }
        const items = await deps.auditSink.query({
          userId: ctx.user.userId,
          ...(args.tool ? { tool: args.tool } : {}),
          ...(args.outcome ? { outcome: args.outcome } : {}),
          ...(args.from ? { from: args.from } : {}),
          ...(args.to ? { to: args.to } : {}),
          limit: args.limit,
        });
        return {
          retentionDays: config.audit.retentionDays,
          count: items.length,
          items: items.map((r) => ({
            ts: r.ts,
            tool: r.tool,
            write: r.write,
            outcome: r.outcome,
            durationMs: r.durationMs,
            ...(r.errorCode ? { errorCode: r.errorCode } : {}),
            ...(r.targetIds ? { targetIds: r.targetIds } : {}),
          })),
        };
      }),
  );

  /* ======================== 写操作（阶段 2，默认关闭） ======================== */

  if (writesEnabled) {
    registerWriteTools({ server, client, config, run, idempotent });
    registerLeaveFlowWriteTools({ server, run, idempotent, client });
  }

  return server;
}

interface WriteToolDeps {
  server: McpServer;
  client: HaisoftClient;
  config: AppConfig;
  run: <T>(
    meta: { tool: string; write?: boolean; args?: unknown; targetIds?: string[] },
    fn: (ctx: RequestContext) => Promise<T>,
  ) => Promise<CallToolResult>;
  idempotent: <T>(
    ctx: RequestContext,
    tool: string,
    args: unknown,
    rawKey: string | undefined,
    fn: () => Promise<T>,
  ) => Promise<{ result: T; replayed: boolean }>;
}

function registerWriteTools(deps: WriteToolDeps): void {
  const { server, client, run, idempotent } = deps;




  server.registerTool(
    'approve_leave_request',
    {
      title: '审批通过',
      description:
        '辅导员审批通过授权范围内的待审批申请。仅「已提交」状态可审批。' +
        '执行前必须向用户确认目标学生与请假时段。',
      inputSchema: reviewShape,
      annotations: WRITE,
    },
    (args) =>
      run({ tool: 'approve_leave_request', write: true, args, targetIds: [args.requestId] }, async (ctx) => {
        requireCounselor(ctx.user);
        const { result, replayed } = await idempotent(
          ctx,
          'approve_leave_request',
          { requestId: args.requestId, comment: args.comment },
          args.idempotencyKey,
          async () => {
            const current = await client.getLeaveRequest(args.requestId);
            assertInScope(ctx.user, current);
            assertStatus(current.status, ['submitted'], '审批');
            return client.reviewLeaveRequest(ctx.user, args.requestId, 'approve', args.comment);
          },
        );
        return { ...toLeaveView(result), replayed };
      }),
  );

  server.registerTool(
    'reject_leave_request',
    {
      title: '驳回申请',
      description:
        '辅导员驳回授权范围内的待审批申请。驳回必须给出理由，' +
        '未提供 comment 时会被拒绝执行。',
      inputSchema: reviewShape,
      annotations: WRITE,
    },
    (args) =>
      run({ tool: 'reject_leave_request', write: true, args, targetIds: [args.requestId] }, async (ctx) => {
        requireCounselor(ctx.user);
        if (!args.comment || args.comment.trim().length < 2) {
          throw invalidArgument('驳回必须填写理由（comment）');
        }
        const { result, replayed } = await idempotent(
          ctx,
          'reject_leave_request',
          { requestId: args.requestId, comment: args.comment },
          args.idempotencyKey,
          async () => {
            const current = await client.getLeaveRequest(args.requestId);
            assertInScope(ctx.user, current);
            assertStatus(current.status, ['submitted'], '驳回');
            return client.reviewLeaveRequest(ctx.user, args.requestId, 'reject', args.comment);
          },
        );
        return { ...toLeaveView(result), replayed };
      }),
  );
}

interface LeaveFlowDeps {
  server: McpServer;
  run: <T>(
    meta: { tool: string; write?: boolean; args?: unknown; targetIds?: string[] },
    fn: (ctx: RequestContext) => Promise<T>,
  ) => Promise<CallToolResult>;
  idempotent: <T>(
    ctx: RequestContext,
    tool: string,
    args: unknown,
    rawKey: string | undefined,
    fn: () => Promise<T>,
  ) => Promise<{ result: T; replayed: boolean }>;
  client: HaisoftClient;
}

/**
 * 请假引导流程的最后一步：提交。
 * 与 create_leave_request 的区别：这里接收的是「已解析并确认过的草稿」，
 * 校验口径与 preview 完全一致，避免预览说可以、提交又报缺字段。
 */
function registerLeaveFlowWriteTools(deps: LeaveFlowDeps): void {
  const { server, run, idempotent, client } = deps;

  server.registerTool(
    'submit_leave_application',
    {
      title: '提交请假申请（第三步）',
      description:
        '把 preview 通过后的草稿正式提交。执行前必须已把 summary 复述给用户并取得确认。' +
        '字段口径与 preview_leave_application 相同；缺项会返回 INVALID_ARGUMENT 并带 missing。' +
        '带幂等保护：重复提交不会生成第二张请假单。',
      inputSchema: {
        ...draftShape,
        idempotencyKey: z
          .string()
          .min(8)
          .max(128)
          .optional()
          .describe('幂等键，可选。不传时按「用户+参数」派生，防止重试重复提交'),
      },
      annotations: WRITE,
    },
    (args) =>
      run({ tool: 'submit_leave_application', write: true, args }, async (ctx) => {
        requireStudent(ctx.user);
        const { draft } = buildDraft(args);
        const evaluation = evaluateDraft(draft, new Date());

        if (evaluation.stage !== 'ready') {
          throw invalidArgument('请假信息尚不完整，未提交', {
            stage: evaluation.stage,
            missing: evaluation.missing,
            errors: evaluation.errors,
            ...(evaluation.timeSuggestions.length > 0
              ? { timeSuggestions: evaluation.timeSuggestions }
              : {}),
          });
        }

        const payload = {
          // 姓名与班级只能来自可信身份，不接受模型传参
          studentName: ctx.user.name,
          ...(ctx.user.classIds[0] ? { className: ctx.user.classIds[0] } : {}),
          leaveType: draft.leaveType as LeaveType,
          category: draft.category as LeaveCategory,
          startAt: draft.startAt as string,
          endAt: draft.endAt as string,
          reason: draft.reason as string,
          ...(draft.destination ? { destination: draft.destination } : {}),
          ...(draft.guardianContact ? { guardianContact: draft.guardianContact } : {}),
          ...(draft.attachments.length > 0 ? { attachments: draft.attachments } : {}),
        };

        const { result, replayed } = await idempotent(
          ctx,
          'submit_leave_application',
          payload,
          args.idempotencyKey,
          () => client.createLeaveRequest(ctx.user.userId, payload),
        );

        return {
          submitted: true,
          replayed,
          requestId: result.id,
          status: result.status,
          statusLabel: '待审批',
          summary: evaluation.summary,
          durationDays: result.durationDays,
          ...(evaluation.warnings.length > 0 ? { warnings: evaluation.warnings } : {}),
          notification: replayed
            ? `重复提交已拦截：沿用首次结果，请假单 ${result.id} 已存在（状态「待审批」），未生成新单`
            : `提交成功：${LEAVE_CATEGORY_LABEL[payload.category]}单 ${result.id} 已提交，当前状态「待审批」，请等待辅导员处理`,
          nextStep: '把 notification 原样告知用户；如需查看进度或历史，调用 list_my_leave_requests',
        };
      }),
  );
}

/** 供测试与诊断使用：当前启用状态下暴露的工具名清单 */
export function toolNames(enableWriteTools: boolean): string[] {
  const identity = ['get_identity_status', 'select_identity', 'login_with_cas'];
  const read = [
    'start_leave_application',
    'preview_leave_application',
    'get_current_user',
    'list_my_leave_requests',
    'list_pending_approvals',
    'query_my_audit_log',
  ];
  const write = ['submit_leave_application', 'approve_leave_request', 'reject_leave_request'];
  return enableWriteTools ? [...identity, ...read, ...write] : [...identity, ...read];
}
