import { Controller } from "@nestjs/common";
import { GrpcMethod } from "@nestjs/microservices";
import { KnowledgePointsService } from "../knowledge-points/knowledge-points.service.js";
import type { KnowledgePoint } from "../knowledge-points/knowledge-points.schema.js";
import type {
  GetPrerequisitesRequest,
  KnowledgePointsResponse,
  GetLearningPathRequest,
  LearningPath,
  AddPrerequisiteRequest,
  RemovePrerequisiteRequest,
  GrpcKnowledgePoint,
  Empty,
} from "./grpc-types.js";

function toGrpcKp(kp: KnowledgePoint): GrpcKnowledgePoint {
  return {
    id: kp.id,
    chapter_id: kp.chapterId,
    title: kp.title,
    description: kp.description ?? "",
    difficulty: kp.difficulty,
    metadata: kp.metadata ?? null,
    created_at: kp.createdAt.getTime(),
    updated_at: kp.updatedAt.getTime(),
  };
}

@Controller()
export class KnowledgeGraphGrpcController {
  constructor(private readonly service: KnowledgePointsService) {}

  @GrpcMethod("KnowledgeGraphService", "GetPrerequisites")
  async getPrerequisites(
    data: GetPrerequisitesRequest,
  ): Promise<KnowledgePointsResponse> {
    // 直接使用 service.getPrerequisites（读 Neo4j 派生数据）
    const prereqs = await this.service.getPrerequisites(
      data.knowledge_point_id,
    );
    // PrerequisiteNode 只含 id + title，需要查 MySQL 补全信息
    const points: GrpcKnowledgePoint[] = [];
    for (const p of prereqs) {
      try {
        const kp = await this.service.getKnowledgePoint(p.id);
        points.push(toGrpcKp(kp));
      } catch {
        // 节点可能已删除，跳过
      }
    }
    return { points };
  }

  @GrpcMethod("KnowledgeGraphService", "GetLearningPath")
  async getLearningPath(_data: GetLearningPathRequest): Promise<LearningPath> {
    // P4 阶段未实现学习路径推荐算法，返回空路径
    // P5+ 引入 AI 服务后实现
    return { points: [], recommended_order: [] };
  }

  @GrpcMethod("KnowledgeGraphService", "AddPrerequisite")
  async addPrerequisite(data: AddPrerequisiteRequest): Promise<Empty> {
    await this.service.addPrerequisite(data.kp_id, data.prerequisite_id);
    return {};
  }

  @GrpcMethod("KnowledgeGraphService", "RemovePrerequisite")
  async removePrerequisite(data: RemovePrerequisiteRequest): Promise<Empty> {
    await this.service.removePrerequisite(data.kp_id, data.prerequisite_id);
    return {};
  }
}
