import "server-only";
import { prisma } from "@/lib/db";
import type { CodingLanguage, CodingSubmissionStatus, CourseLevel, PublishStatus, Role } from "@prisma/client";

/**
 * Coding lab and robot simulator reads.
 *
 * Access: published projects/challenges are visible to every signed-in user
 * (they are the practice surface); drafts are staff-only.
 */

export interface CodingScope {
  userId: string;
  role: Role;
}

// ---------------------------------------------------------------------------
// Coding projects
// ---------------------------------------------------------------------------

export interface CodingProjectListItem {
  id: string;
  title: string;
  slug: string;
  description: string;
  language: CodingLanguage;
  difficulty: CourseLevel;
  status: PublishStatus;
  xpReward: number;
  courseTitle: string | null;
  courseCoverColor: string | null;
  testCount: number;
  hintCount: number;
  attemptCount: number;
  /** The signed-in user's best attempt status, if any. */
  bestStatus: CodingSubmissionStatus | null;
  bestScore: number | null;
  passedAt: Date | null;
  skills: { name: string; icon: string; color: string }[];
}

export interface CodingFilters {
  difficulty?: CourseLevel;
  language?: CodingLanguage;
  courseId?: string;
  status?: "all" | "solved" | "unsolved";
}

export async function listCodingProjects(
  scope: CodingScope,
  filters: CodingFilters = {}
): Promise<CodingProjectListItem[]> {
  const projects = await prisma.codingProject.findMany({
    where: {
      AND: [
        scope.role === "STUDENT" ? { status: "PUBLISHED" as const } : {},
        filters.difficulty ? { difficulty: filters.difficulty } : {},
        filters.language ? { language: filters.language } : {},
        filters.courseId ? { courseId: filters.courseId } : {},
      ],
    },
    orderBy: [{ orderIndex: "asc" }, { createdAt: "asc" }],
    select: {
      id: true,
      title: true,
      slug: true,
      description: true,
      language: true,
      difficulty: true,
      status: true,
      xpReward: true,
      tests: true,
      hints: true,
      course: { select: { title: true, coverColor: true } },
      skills: {
        select: { skill: { select: { name: true, icon: true, color: true } } },
      },
      submissions: {
        where: { studentId: scope.userId },
        orderBy: { score: "desc" },
        select: { status: true, score: true, createdAt: true },
        take: 1,
      },
      _count: { select: { submissions: true } },
    },
  });

  const rows: CodingProjectListItem[] = projects.map((project) => {
    const best = project.submissions[0];
    const tests = Array.isArray(project.tests) ? project.tests : [];
    return {
      id: project.id,
      title: project.title,
      slug: project.slug,
      description: project.description,
      language: project.language,
      difficulty: project.difficulty,
      status: project.status,
      xpReward: project.xpReward,
      courseTitle: project.course?.title ?? null,
      courseCoverColor: project.course?.coverColor ?? null,
      testCount: tests.length,
      hintCount: project.hints.length,
      attemptCount: project._count.submissions,
      bestStatus: best?.status ?? null,
      bestScore: best?.score ?? null,
      passedAt: best?.status === "PASSED" ? best.createdAt : null,
      skills: project.skills.map((entry) => entry.skill),
    };
  });

  if (!filters.status || filters.status === "all") return rows;
  return rows.filter((row) =>
    filters.status === "solved" ? row.bestStatus === "PASSED" : row.bestStatus !== "PASSED"
  );
}

export interface CodingProjectDetail {
  id: string;
  title: string;
  slug: string;
  description: string;
  brief: string | null;
  language: CodingLanguage;
  difficulty: CourseLevel;
  status: PublishStatus;
  starterCode: string;
  solutionCode: string | null;
  hints: string[];
  xpReward: number;
  course: { id: string; title: string } | null;
  createdBy: string;
  tests: { name: string; test: string }[];
  skills: { id: string; name: string; icon: string; color: string }[];
  canManage: boolean;
  stats: { attempts: number; solvers: number; passRate: number };
  myAttempts: {
    id: string;
    status: CodingSubmissionStatus;
    score: number;
    passedTests: number;
    totalTests: number;
    createdAt: Date;
  }[];
}

/** Normalise the `tests` JSON column into typed test cases. */
function parseTests(value: unknown): { name: string; test: string }[] {
  if (!Array.isArray(value)) return [];
  return value.flatMap((item) => {
    if (item && typeof item === "object" && "name" in item && "test" in item) {
      const name = item.name;
      const test = item.test;
      if (typeof name === "string" && typeof test === "string") return [{ name, test }];
    }
    return [];
  });
}

export async function getCodingProject(
  scope: CodingScope,
  projectId: string
): Promise<CodingProjectDetail | null> {
  const project = await prisma.codingProject.findFirst({
    where: {
      id: projectId,
      ...(scope.role === "STUDENT" ? { status: "PUBLISHED" as const } : {}),
    },
    select: {
      id: true,
      title: true,
      slug: true,
      description: true,
      brief: true,
      language: true,
      difficulty: true,
      status: true,
      starterCode: true,
      solutionCode: true,
      hints: true,
      xpReward: true,
      tests: true,
      createdById: true,
      course: { select: { id: true, title: true } },
      skills: {
        select: { skill: { select: { id: true, name: true, icon: true, color: true } } },
      },
      submissions: {
        where: { studentId: scope.userId },
        orderBy: { createdAt: "desc" },
        take: 10,
        select: {
          id: true,
          status: true,
          score: true,
          passedTests: true,
          totalTests: true,
          createdAt: true,
        },
      },
    },
  });

  if (!project) return null;

  const [attempts, solvers] = await Promise.all([
    prisma.codingSubmission.count({ where: { projectId } }),
    prisma.codingSubmission
      .findMany({
        where: { projectId, status: "PASSED" },
        select: { studentId: true },
        distinct: ["studentId"],
      })
      .then((rows) => rows.length),
  ]);

  return {
    id: project.id,
    title: project.title,
    slug: project.slug,
    description: project.description,
    brief: project.brief,
    language: project.language,
    difficulty: project.difficulty,
    status: project.status,
    starterCode: project.starterCode,
    solutionCode: project.solutionCode,
    hints: project.hints,
    xpReward: project.xpReward,
    course: project.course,
    createdBy: project.createdById,
    tests: parseTests(project.tests),
    skills: project.skills.map((entry) => entry.skill),
    canManage: scope.role === "ADMIN" || scope.userId === project.createdById,
    stats: {
      attempts,
      solvers,
      passRate: attempts === 0 ? 0 : Math.round((solvers / attempts) * 100),
    },
    myAttempts: project.submissions,
  };
}

export interface CodingCourseOption {
  id: string;
  title: string;
}

/**
 * Courses a coding project may be attached to.
 *
 * Scoped to what the caller can actually see: staff get the courses they teach
 * (admins get all), students only the published courses they are enrolled in.
 * Returning every course platform-wide leaked other teachers' drafts and
 * unpublished titles to any viewer.
 */
export async function listCodingCourseOptions(
  scope: CodingScope
): Promise<CodingCourseOption[]> {
  const where =
    scope.role === "ADMIN"
      ? {}
      : scope.role === "TEACHER"
        ? { OR: [{ teacherId: scope.userId }, { classroom: { teacherId: scope.userId } }] }
        : {
            status: "PUBLISHED" as const,
            OR: [
              { enrollments: { some: { studentId: scope.userId, status: "ACTIVE" as const } } },
              {
                classroom: {
                  enrollments: { some: { studentId: scope.userId, status: "ACTIVE" as const } },
                },
              },
            ],
          };

  return prisma.course.findMany({
    where,
    orderBy: { title: "asc" },
    select: { id: true, title: true },
  });
}

export async function listSkillOptions() {
  return prisma.skill.findMany({
    orderBy: [{ orderIndex: "asc" }, { name: "asc" }],
    select: { id: true, name: true, icon: true, color: true },
  });
}

// ---------------------------------------------------------------------------
// Simulator challenges
// ---------------------------------------------------------------------------

export interface SimulatorChallengeListItem {
  id: string;
  slug: string;
  title: string;
  description: string;
  difficulty: CourseLevel;
  gridWidth: number;
  gridHeight: number;
  parSteps: number;
  maxSteps: number;
  starCount: number;
  xpReward: number;
  status: PublishStatus;
  attemptCount: number;
  solved: boolean;
  bestSteps: number | null;
  bestStars: number | null;
  bestScore: number | null;
}

export async function listSimulatorChallenges(
  scope: CodingScope,
  filters: { difficulty?: CourseLevel; status?: "all" | "solved" | "unsolved" } = {}
): Promise<SimulatorChallengeListItem[]> {
  const challenges = await prisma.simulatorChallenge.findMany({
    where: {
      AND: [
        scope.role === "STUDENT" ? { status: "PUBLISHED" as const } : {},
        filters.difficulty ? { difficulty: filters.difficulty } : {},
      ],
    },
    orderBy: [{ orderIndex: "asc" }, { createdAt: "asc" }],
    select: {
      id: true,
      slug: true,
      title: true,
      description: true,
      difficulty: true,
      gridWidth: true,
      gridHeight: true,
      parSteps: true,
      maxSteps: true,
      stars: true,
      xpReward: true,
      status: true,
      attempts: {
        where: { userId: scope.userId },
        orderBy: [{ success: "desc" }, { score: "desc" }],
        take: 1,
        select: { success: true, stepsUsed: true, starsEarned: true, score: true },
      },
      _count: { select: { attempts: true } },
    },
  });

  const rows: SimulatorChallengeListItem[] = challenges.map((challenge) => {
    const best = challenge.attempts[0];
    const stars = Array.isArray(challenge.stars) ? challenge.stars : [];
    return {
      id: challenge.id,
      slug: challenge.slug,
      title: challenge.title,
      description: challenge.description,
      difficulty: challenge.difficulty,
      gridWidth: challenge.gridWidth,
      gridHeight: challenge.gridHeight,
      parSteps: challenge.parSteps,
      maxSteps: challenge.maxSteps,
      starCount: stars.length,
      xpReward: challenge.xpReward,
      status: challenge.status,
      attemptCount: challenge._count.attempts,
      solved: best?.success ?? false,
      bestSteps: best?.success ? best.stepsUsed : null,
      bestStars: best?.success ? best.starsEarned : null,
      bestScore: best?.success ? best.score : null,
    };
  });

  if (!filters.status || filters.status === "all") return rows;
  return rows.filter((row) => (filters.status === "solved" ? row.solved : !row.solved));
}

export interface SimulatorChallengeDetail {
  id: string;
  slug: string;
  title: string;
  description: string;
  difficulty: CourseLevel;
  gridWidth: number;
  gridHeight: number;
  walls: [number, number][];
  startX: number;
  startY: number;
  startDir: string;
  goalX: number;
  goalY: number;
  stars: [number, number][];
  maxSteps: number;
  parSteps: number;
  starterCode: string;
  solutionCode: string | null;
  hints: string[];
  xpReward: number;
  status: PublishStatus;
  canManage: boolean;
  myAttempts: {
    id: string;
    program: string;
    success: boolean;
    stepsUsed: number;
    starsEarned: number;
    score: number;
    createdAt: Date;
  }[];
}

/** Coerce a JSON column into `[x, y]` pairs, ignoring malformed entries. */
function parsePairs(value: unknown): [number, number][] {
  if (!Array.isArray(value)) return [];
  return value.flatMap((item) => {
    if (Array.isArray(item) && item.length === 2 && typeof item[0] === "number" && typeof item[1] === "number") {
      return [[item[0], item[1]] as [number, number]];
    }
    return [];
  });
}

export async function getSimulatorChallenge(
  scope: CodingScope,
  challengeId: string
): Promise<SimulatorChallengeDetail | null> {
  const challenge = await prisma.simulatorChallenge.findFirst({
    where: {
      id: challengeId,
      ...(scope.role === "STUDENT" ? { status: "PUBLISHED" as const } : {}),
    },
    select: {
      id: true,
      slug: true,
      title: true,
      description: true,
      difficulty: true,
      gridWidth: true,
      gridHeight: true,
      walls: true,
      startX: true,
      startY: true,
      startDir: true,
      goalX: true,
      goalY: true,
      stars: true,
      maxSteps: true,
      parSteps: true,
      starterCode: true,
      solutionCode: true,
      hints: true,
      xpReward: true,
      status: true,
      attempts: {
        where: { userId: scope.userId },
        orderBy: { createdAt: "desc" },
        take: 10,
        select: {
          id: true,
          program: true,
          success: true,
          stepsUsed: true,
          starsEarned: true,
          score: true,
          createdAt: true,
        },
      },
    },
  });

  if (!challenge) return null;

  return {
    id: challenge.id,
    slug: challenge.slug,
    title: challenge.title,
    description: challenge.description,
    difficulty: challenge.difficulty,
    gridWidth: challenge.gridWidth,
    gridHeight: challenge.gridHeight,
    walls: parsePairs(challenge.walls),
    startX: challenge.startX,
    startY: challenge.startY,
    startDir: challenge.startDir,
    goalX: challenge.goalX,
    goalY: challenge.goalY,
    stars: parsePairs(challenge.stars),
    maxSteps: challenge.maxSteps,
    parSteps: challenge.parSteps,
    starterCode: challenge.starterCode,
    solutionCode: challenge.solutionCode,
    hints: challenge.hints,
    xpReward: challenge.xpReward,
    status: challenge.status,
    canManage: scope.role === "ADMIN",
    myAttempts: challenge.attempts,
  };
}

/** The learner's most recent submitted code for a project, or an empty string. */
export async function getLatestCodingCode(projectId: string, studentId: string): Promise<string> {
  const latest = await prisma.codingSubmission.findFirst({
    where: { projectId, studentId },
    orderBy: { createdAt: "desc" },
    select: { code: true },
  });
  return latest?.code ?? "";
}

export interface LabSummary {
  projectsTotal: number;
  projectsSolved: number;
  challengesTotal: number;
  challengesSolved: number;
  totalXpFromLab: number;
  skillsEarned: number;
  recentRuns: {
    id: string;
    kind: "project" | "simulator";
    title: string;
    status: string;
    score: number;
    at: Date;
  }[];
}

/** Headline lab statistics for the signed-in learner. */
export async function getLabSummary(scope: CodingScope): Promise<LabSummary> {
  const [
    projectsTotal,
    projectsSolved,
    challengesTotal,
    challengesSolved,
    xpAgg,
    skillsEarned,
    projectRuns,
    simRuns,
  ] = await Promise.all([
    prisma.codingProject.count({ where: { status: "PUBLISHED" } }),
    prisma.codingSubmission
      .findMany({ where: { studentId: scope.userId, status: "PASSED" }, select: { projectId: true }, distinct: ["projectId"] })
      .then((rows) => rows.length),
    prisma.simulatorChallenge.count({ where: { status: "PUBLISHED" } }),
    prisma.simulatorAttempt
      .findMany({ where: { userId: scope.userId, success: true }, select: { challengeId: true }, distinct: ["challengeId"] })
      .then((rows) => rows.length),
    prisma.xpEvent.aggregate({
      where: { userId: scope.userId, source: { in: ["CODING_PROJECT", "SIMULATOR"] } },
      _sum: { amount: true },
    }),
    prisma.userSkill.count({ where: { userId: scope.userId } }),
    prisma.codingSubmission.findMany({
      where: { studentId: scope.userId },
      orderBy: { createdAt: "desc" },
      take: 6,
      select: {
        id: true,
        status: true,
        score: true,
        createdAt: true,
        project: { select: { title: true } },
      },
    }),
    prisma.simulatorAttempt.findMany({
      where: { userId: scope.userId },
      orderBy: { createdAt: "desc" },
      take: 6,
      select: {
        id: true,
        success: true,
        score: true,
        createdAt: true,
        challenge: { select: { title: true } },
      },
    }),
  ]);

  const recentRuns = [
    ...projectRuns.map((run) => ({
      id: run.id,
      kind: "project" as const,
      title: run.project.title,
      status: run.status as string,
      score: run.score,
      at: run.createdAt,
    })),
    ...simRuns.map((run) => ({
      id: run.id,
      kind: "simulator" as const,
      title: run.challenge.title,
      status: run.success ? "PASSED" : "FAILED",
      score: run.score,
      at: run.createdAt,
    })),
  ]
    .sort((a, b) => b.at.getTime() - a.at.getTime())
    .slice(0, 8);

  return {
    projectsTotal,
    projectsSolved,
    challengesTotal,
    challengesSolved,
    totalXpFromLab: xpAgg._sum.amount ?? 0,
    skillsEarned,
    recentRuns,
  };
}
