import { protectedProcedure, router } from "../_core/trpc.ts";
import { TRPCError } from "@trpc/server";
import { z } from "zod";
import { invokeLLM } from "../_core/llm.ts";
import { getAnalyticsSummary, getFraudAlerts, getAuditLogs, getDb } from "../db.ts";
import { desc } from "drizzle-orm";
import { gameSessions, transactions } from "../../drizzle/schema.ts";

const aiProcedure = protectedProcedure.use(({ ctx, next }) => {
  if (ctx.user.role !== "admin" && ctx.user.role !== "staff") {
    throw new TRPCError({ code: "FORBIDDEN", message: "Staff or Admin access required" });
  }
  return next({ ctx });
});

async function buildPlatformContext(): Promise<string> {
  const summary = await getAnalyticsSummary();
  const alerts = await getFraudAlerts("open", 10);
  const recentLogs = await getAuditLogs(20, 0);

  return `
You are the CoinKrazy AI Employee Assistant — an intelligent operations assistant for CoinKrazy.com, a Sweepstakes Social Casino platform.

PLATFORM CONTEXT:
- Total Users: ${summary?.totalUsers ?? "N/A"}
- Active Today: ${summary?.activeToday ?? "N/A"}
- Total Transactions: ${summary?.totalTransactions ?? "N/A"}
- Total Volume: $${summary?.totalVolume ?? "N/A"}
- Pending KYC Reviews: ${summary?.pendingKyc ?? "N/A"}
- Open Fraud Alerts: ${summary?.openAlerts ?? "N/A"}

OPEN FRAUD ALERTS (${alerts.length}):
${alerts.slice(0, 5).map(a => `- User ${(a as any).user?.username ?? (a as any).alert?.userId}: ${(a as any).alert?.alertType} (${(a as any).alert?.severity}) - ${(a as any).alert?.description}`).join("\n")}

RECENT AUDIT EVENTS:
${recentLogs.slice(0, 10).map(l => `- [${l.category}] ${l.action} by actor ${l.actorId} at ${new Date(l.createdAt).toISOString()}`).join("\n")}

CURRENCIES:
- Gold Coins (GC): Fun currency, no cash value
- Sweeps Coins (SC): Redeemable at 1 SC = 1 USD

COMPLIANCE:
- Sweepstakes model (no purchase necessary)
- KYC/AML required for SC redemption
- Restricted states: WA, ID, MT, NV, KY

You can answer questions about player behavior, fraud patterns, platform metrics, compliance, and operational issues.
Be concise, professional, and data-driven in your responses.
`;
}

export const aiAssistantRouter = router({
  chat: aiProcedure
    .input(z.object({
      message: z.string().min(1).max(2000),
      history: z.array(z.object({ role: z.enum(["user", "assistant"]), content: z.string() })).default([]),
    }))
    .mutation(async ({ input }) => {
      const systemContext = await buildPlatformContext();
      const response = await invokeLLM({
        messages: [
          { role: "system", content: systemContext },
          ...input.history.slice(-10),
          { role: "user", content: input.message },
        ],
      });
      return { response: response.choices[0].message.content ?? "I couldn't generate a response." };
    }),

  generateDailyReport: aiProcedure.mutation(async () => {
    const summary = await getAnalyticsSummary();
    const alerts = await getFraudAlerts("open", 20);
    const db = await getDb();
    let topGames: any[] = [];
    if (db) {
      const result = await db.select().from(gameSessions).orderBy(desc(gameSessions.createdAt)).limit(100);
      topGames = result;
    }

    const prompt = `Generate a comprehensive daily operations report for CoinKrazy.com with the following data:

Platform Metrics:
- Total Users: ${summary?.totalUsers}
- Active Today: ${summary?.activeToday}
- Total Volume: $${summary?.totalVolume}
- Pending KYC: ${summary?.pendingKyc}
- Open Fraud Alerts: ${summary?.openAlerts}

Open Fraud Alerts: ${alerts.length} alerts requiring attention
Recent Game Sessions: ${topGames.length} sessions in last batch

Please provide:
1. Executive Summary
2. Key Performance Indicators
3. Risk & Compliance Status
4. Fraud Alert Summary
5. Recommended Actions for Today
6. Player Engagement Insights

Format as a professional operations report.`;

    const response = await invokeLLM({
      messages: [
        { role: "system", content: "You are the CoinKrazy AI Operations Manager. Generate detailed, professional daily reports." },
        { role: "user", content: prompt },
      ],
    });

    return { report: response.choices[0].message.content ?? "Report generation failed." };
  }),

  analyzeFraud: aiProcedure
    .input(z.object({ userId: z.number() }))
    .mutation(async ({ input }) => {
      const db = await getDb();
      if (!db) throw new Error("DB unavailable");
      const { eq } = await import("drizzle-orm");
      const userTransactions = await db.select().from(transactions).where(eq(transactions.userId, input.userId)).orderBy(desc(transactions.createdAt)).limit(50);

      const response = await invokeLLM({
        messages: [
          { role: "system", content: "You are a fraud analyst for CoinKrazy.com, a sweepstakes casino. Analyze transaction patterns for suspicious behavior." },
          { role: "user", content: `Analyze these ${userTransactions.length} transactions for user ID ${input.userId} and identify any suspicious patterns, bonus abuse, or fraud indicators:\n\n${JSON.stringify(userTransactions.slice(0, 20), null, 2)}` },
        ],
      });

      return { analysis: response.choices[0].message.content ?? "Analysis failed." };
    }),

  getSupportScript: aiProcedure
    .input(z.object({ issue: z.string().min(1), context: z.string().optional() }))
    .mutation(async ({ input }) => {
      const response = await invokeLLM({
        messages: [
          { role: "system", content: "You are a customer support specialist for CoinKrazy.com. Provide helpful, professional, and compliant support scripts for staff to use with players. Always maintain a friendly, helpful tone while adhering to sweepstakes regulations." },
          { role: "user", content: `Create a customer support response script for this issue: "${input.issue}"${input.context ? `\nContext: ${input.context}` : ""}` },
        ],
      });
      return { script: response.choices[0].message.content ?? "Script generation failed." };
    }),
});
