import { eq } from "drizzle-orm";
import { schema } from "@app/database";
import type { AamosTaskType } from "@app/ai-contracts";
import type { WorkerContext } from "../context.js";
import { getLocaleContext } from "../locale.js";
import type { LocaleContext } from "@app/shared-types";

/**
 * Bild-/OCR-jobb (spec §54): hämtar scan_job, anropar AAMOS med kontraktvaliderad
 * input/output, sparar resultatet och sätter awaiting_confirmation.
 * Användaren bekräftar ALLTID innan lagret röres (spec §61.5).
 */
export async function processScanJob(ctx: WorkerContext, scanJobId: string): Promise<void> {
  const [job] = await ctx.db
    .select()
    .from(schema.scanJobs)
    .where(eq(schema.scanJobs.id, scanJobId))
    .limit(1);
  if (!job) throw new Error(`scan_job ${scanJobId} finns inte`);
  if (job.status === "completed" || job.status === "awaiting_confirmation") return; // idempotent

  await ctx.db
    .update(schema.scanJobs)
    .set({ status: "running", attempts: job.attempts + 1, updatedAt: new Date() })
    .where(eq(schema.scanJobs.id, scanJobId));

  const imageUrls = job.s3Keys.map((k) => ctx.readUrl(k));
  const localeContext = await getLocaleContext(ctx, job.userId);
  const consents = await loadConsentFlags(ctx, job.userId);

  const started = Date.now();
  const result = await runAamosForJob(
    ctx,
    job.jobType as AamosTaskType,
    job.scanType,
    imageUrls,
    job.context,
    localeContext,
  );

  if (result.status === "failed" || result.output == null) {
    await ctx.db
      .update(schema.scanJobs)
      .set({
        status: "failed",
        error: result.error ?? "AI-analysen misslyckades. Försök igen eller registrera manuellt.",
        latencyMs: Date.now() - started,
        updatedAt: new Date(),
      })
      .where(eq(schema.scanJobs.id, scanJobId));
    return;
  }

  await ctx.db
    .update(schema.scanJobs)
    .set({
      status: "awaiting_confirmation",
      result: result.output as Record<string, unknown>,
      modelVersion: result.modelVersion ?? null,
      promptVersion: result.promptVersion ?? null,
      latencyMs: result.latencyMs ?? Date.now() - started,
      costUsd: result.costUsd ?? null,
      updatedAt: new Date(),
    })
    .where(eq(schema.scanJobs.id, scanJobId));

  // MEAL_PHOTO_ANALYZED-event för tallriksfoton (spec §55)
  if (job.jobType === "ANALYZE_MEAL_IMAGE") {
    const output = result.output as {
      kcalRange?: { mostLikely: number } | null;
      matchesRecipeContext?: boolean | null;
    };
    await ctx.db.insert(schema.domainEvents).values({
      type: "MEAL_PHOTO_ANALYZED",
      userId: job.userId,
      householdId: job.householdId,
      payload: {
        scanJobId,
        matched: output.matchesRecipeContext ?? false,
        kcalMostLikely: output.kcalRange?.mostLikely ?? null,
      },
    });
  }
  void consents;
}

async function runAamosForJob(
  ctx: WorkerContext,
  jobType: AamosTaskType,
  scanType: string,
  imageUrls: string[],
  context: unknown,
  localeContext: LocaleContext,
) {
  switch (jobType) {
    case "ANALYZE_FRIDGE_IMAGE":
    case "ANALYZE_PANTRY_IMAGE":
      return ctx.aamos.runTask(
        jobType,
        {
          imageUrls,
          locationType: scanType,
          marketLocale: localeContext.languageTag,
          knownItems: [],
        },
        { localeContext },
      );
    case "ANALYZE_MEAL_IMAGE": {
      const recipeContext = await buildRecipeContext(ctx, context);
      return ctx.aamos.runTask(
        "ANALYZE_MEAL_IMAGE",
        { imageUrls, recipeContext, marketLocale: localeContext.languageTag },
        { localeContext },
      );
    }
    case "READ_RECEIPT":
      return ctx.aamos.runTask(
        "READ_RECEIPT",
        { imageUrls, marketLocale: localeContext.languageTag },
        { localeContext },
      );
    case "READ_NUTRITION_LABEL":
      return ctx.aamos.runTask(
        "READ_NUTRITION_LABEL",
        { imageUrls, marketLocale: localeContext.languageTag },
        { localeContext },
      );
    case "READ_EXPIRY_DATE":
      return ctx.aamos.runTask(
        "READ_EXPIRY_DATE",
        { imageUrls: imageUrls.slice(0, 2) },
        { localeContext },
      );
    default:
      throw new Error(`Jobbtypen ${jobType} hanteras inte av scan-processorn`);
  }
}

async function buildRecipeContext(ctx: WorkerContext, context: unknown) {
  if (
    typeof context !== "object" ||
    context === null ||
    typeof (context as { recipeId?: unknown }).recipeId !== "string"
  ) {
    return null;
  }
  const recipeId = (context as { recipeId: string }).recipeId;
  const [recipe] = await ctx.db
    .select({
      id: schema.recipes.id,
      titleSv: schema.recipes.titleSv,
      nutritionPerPortion: schema.recipes.nutritionPerPortion,
      portions: schema.recipes.portions,
    })
    .from(schema.recipes)
    .where(eq(schema.recipes.id, recipeId))
    .limit(1);
  if (!recipe) return null;
  return {
    recipeId: recipe.id,
    titleSv: recipe.titleSv,
    nutritionPerPortion: recipe.nutritionPerPortion as unknown as Record<string, number>,
    portions: recipe.portions,
  };
}

async function loadConsentFlags(ctx: WorkerContext, userId: string) {
  const consents = await ctx.db
    .select()
    .from(schema.userConsents)
    .where(eq(schema.userConsents.userId, userId));
  const get = (kind: string) => consents.find((c) => c.kind === kind)?.status === "granted";
  return {
    personalization: get("personalization"),
    anonymizedImprovement: get("anonymized_improvement"),
    imageTraining: get("image_training"),
  };
}
