import fs from "fs/promises";
import fsSync from "fs";
import path from "path";
import { storage } from "../../storage";
import { emptyFolderContainingFile } from "../../utils/emptyTempFolder";
import {
  forwardToSeleniumBcbsMaEligibilityAgent,
  getSeleniumBcbsMaSessionStatus,
} from "../../services/seleniumBcbsMaInsuranceEligibilityClient";
import { splitName, createOrUpdatePatientByInsuranceId } from "./_shared";
import { io } from "../../socket";

function log(tag: string, msg: string, ctx?: any) {
  console.log(`${new Date().toISOString()} [${tag}] ${msg}`, ctx ?? "");
}

function emitToSocket(socketId: string | undefined, event: string, payload: any) {
  if (!socketId || !io) return;
  try {
    const socket = io.sockets.sockets.get(socketId);
    if (socket) socket.emit(event, payload);
  } catch (err: any) {
    log("bcbs-ma-processor", `emit failed for ${event}`, { err: err?.message });
  }
}

export interface BcbsMaEligibilityProcessorInput {
  enrichedPayload: any;
  userId: number;
  insuranceId: string;
  formFirstName?: string;
  formLastName?: string;
  formDob?: string;
  socketId?: string;
}

export interface BcbsMaEligibilityProcessorResult {
  patientUpdateStatus?: string;
  pdfUploadStatus?: string;
  pdfFileId?: number | null;
  pdfFilename?: string | null;
}

async function processBcbsMaResult(
  userId: number,
  insuranceId: string,
  formFirstName: string | undefined,
  formLastName: string | undefined,
  formDob: string | undefined,
  seleniumResult: any
): Promise<BcbsMaEligibilityProcessorResult> {
  const output: BcbsMaEligibilityProcessorResult = {};
  let createdPdfFileId: number | null = null;

  try {
    // Prefer names extracted from the BCBS MA results page (Demographic Information section)
    const firstName: string =
      (typeof seleniumResult?.firstName === "string" && seleniumResult.firstName.trim())
        ? seleniumResult.firstName.trim()
        : (formFirstName ?? "");
    const lastName: string =
      (typeof seleniumResult?.lastName === "string" && seleniumResult.lastName.trim())
        ? seleniumResult.lastName.trim()
        : (formLastName ?? "");

    const normalizedInsuranceId = insuranceId.replace(/\s+/g, "");

    // Identify patient by member ID + DOB — not member ID alone.
    // Dependents (e.g. Maria) share the subscriber's member ID but have a different DOB.
    const dobDate = formDob ? new Date(formDob) : null;

    let patient = dobDate
      ? await storage.getPatientByInsuranceIdAndDob(normalizedInsuranceId, dobDate)
      : await storage.getPatientByInsuranceId(normalizedInsuranceId);

    if (patient) {
      // Existing patient found by insuranceId + DOB — update name
      log("bcbs-ma-processor", `Patient matched by insuranceId+DOB id=${patient.id}`);
      await storage.updatePatient(patient.id, { firstName, lastName });
    } else {
      // No match — create a brand new patient record.
      // Do NOT use createOrUpdatePatientByInsuranceId here because it looks up by
      // insuranceId alone and would overwrite the subscriber (e.g. Hugo) instead of
      // creating a new record for the dependent (e.g. Maria).
      log("bcbs-ma-processor", "No patient matched by insuranceId+DOB — creating new patient record");
      try {
        await storage.createPatient({
          firstName,
          lastName,
          insuranceId: normalizedInsuranceId,
          dateOfBirth: dobDate ?? undefined,
          gender: "",
          phone: "",
          userId,
        } as any);
      } catch (createErr: any) {
        log("bcbs-ma-processor", `createPatient failed: ${createErr?.message}`, createErr);
        throw createErr;
      }
      patient = dobDate
        ? await storage.getPatientByInsuranceIdAndDob(normalizedInsuranceId, dobDate)
        : await storage.getPatientByInsuranceId(normalizedInsuranceId);
    }

    if (!patient?.id) {
      output.patientUpdateStatus = "Patient not found; no update performed";
      return output;
    }

    const eligStatus = (seleniumResult?.eligibility ?? "").toLowerCase();
    const newStatus =
      eligStatus === "eligible" || eligStatus === "active" ? "ACTIVE" : "INACTIVE";
    await storage.updatePatient(patient.id, {
      status: newStatus,
      insuranceProvider: "BCBS MA",
    });
    output.patientUpdateStatus = `Patient status updated to ${newStatus}`;

    // Save PDF
    let pdfBuffer: Buffer | null = null;
    let pdfFilename: string | null = null;
    const pdfPath: string | null = seleniumResult?.pdf_path ?? null;

    if (pdfPath && fsSync.existsSync(pdfPath)) {
      try {
        pdfBuffer = await fs.readFile(pdfPath);
        pdfFilename = path.basename(pdfPath);
      } catch (e: any) {
        output.pdfUploadStatus = `Failed to read PDF: ${e.message}`;
      }
    } else {
      output.pdfUploadStatus = "No valid PDF path from Selenium.";
    }

    if (pdfBuffer && pdfFilename) {
      const groupTitleKey = "ELIGIBILITY_STATUS";
      const groupTitle = "Eligibility Status";
      let group = await storage.findPdfGroupByPatientTitleKey(patient.id, groupTitleKey);
      if (!group) group = await storage.createPdfGroup(patient.id, groupTitle, groupTitleKey);
      if (!group?.id) throw new Error("PDF group creation failed");
      const created = await storage.createPdfFile(group.id, pdfFilename, pdfBuffer);
      if (created && typeof created === "object" && "id" in created) {
        createdPdfFileId = Number(created.id);
      }
      output.pdfUploadStatus = `PDF saved to group: ${group.title}`;
      output.pdfFilename = pdfFilename;
    }

    output.pdfFileId = createdPdfFileId;
    return output;
  } catch (err: any) {
    log("bcbs-ma-processor", `processBcbsMaResult ERROR: ${err?.message}`, err);
    return {
      ...output,
      pdfUploadStatus: output.pdfUploadStatus ?? `Processing failed: ${err?.message}`,
      pdfFileId: createdPdfFileId,
    };
  } finally {
    const cleanupPath = seleniumResult?.pdf_path ?? null;
    if (cleanupPath) {
      try {
        await emptyFolderContainingFile(cleanupPath);
      } catch (_) {}
    }
  }
}

async function pollUntilDone(
  sessionId: string,
  socketId: string | undefined,
  jobId: string,
  pollTimeoutMs = 8 * 60 * 1000  // 8 min — accounts for fresh login + OTP wait
): Promise<any> {
  const maxAttempts = 960;  // 960 × 500ms = 8 min
  const pollIntervalMs = 500;
  const maxTransientErrors = 12;
  const noProgressLimit = 120;

  let transientErrors = 0;
  let consecutiveNoProgress = 0;
  let lastStatus: string | null = null;
  const deadline = Date.now() + pollTimeoutMs;

  for (let attempt = 0; attempt < maxAttempts; attempt++) {
    if (Date.now() > deadline) {
      throw new Error(`BCBS MA polling timeout (${Math.round(pollTimeoutMs / 1000)}s) for session ${sessionId}`);
    }

    try {
      const st = await getSeleniumBcbsMaSessionStatus(sessionId);
      const status: string = st?.status ?? "unknown";
      transientErrors = 0;

      const isTerminal = status === "completed" || status === "error" || status === "not_found";
      if (status === lastStatus && !isTerminal) consecutiveNoProgress++;
      else consecutiveNoProgress = 0;
      lastStatus = status;

      if (consecutiveNoProgress >= noProgressLimit) {
        throw new Error(`No progress from Python agent (status="${status}") after ${consecutiveNoProgress} polls`);
      }

      if (status === "waiting_for_otp") {
        emitToSocket(socketId, "selenium:otp_required", {
          session_id: sessionId,
          jobId,
          message: "OTP required. Please enter the 6-digit code from the BCBS MA email.",
        });
        await new Promise((r) => setTimeout(r, pollIntervalMs));
        continue;
      }

      if (status === "completed") return st.result;

      if (status === "error" || status === "not_found") {
        throw new Error(st?.message || `BCBS MA session ended with status: ${status}`);
      }

      await new Promise((r) => setTimeout(r, pollIntervalMs));
    } catch (err: any) {
      const isTerminal =
        err?.response?.status === 404 ||
        (typeof err?.message === "string" &&
          (err.message.includes("not_found") ||
            err.message.includes("polling timeout") ||
            err.message.includes("No progress")));

      if (isTerminal) throw err;

      transientErrors++;
      if (transientErrors > maxTransientErrors) {
        throw new Error(`Too many transient network errors polling BCBS MA session ${sessionId}`);
      }
      const backoff = Math.min(30_000, 500 * Math.pow(2, transientErrors - 1));
      await new Promise((r) => setTimeout(r, backoff));
    }
  }

  throw new Error(`BCBS MA polling exhausted all attempts for session ${sessionId}`);
}

export async function runBcbsMaEligibilityProcessor(
  input: BcbsMaEligibilityProcessorInput,
  jobId: string
): Promise<BcbsMaEligibilityProcessorResult> {
  const { enrichedPayload, userId, insuranceId, formFirstName, formLastName, formDob, socketId } = input;

  log("bcbs-ma-processor", "starting Python agent session", { insuranceId });
  const agentResp = await forwardToSeleniumBcbsMaEligibilityAgent(enrichedPayload);

  if (!agentResp?.session_id) {
    throw new Error("Python agent did not return a session_id for BCBS MA eligibility");
  }

  const sessionId = agentResp.session_id as string;
  log("bcbs-ma-processor", "got session_id", { sessionId });

  emitToSocket(socketId, "selenium:bcbs_ma_session_started", { session_id: sessionId, jobId });

  const seleniumResult = await pollUntilDone(sessionId, socketId, jobId);

  if (!seleniumResult || seleniumResult.status === "error") {
    throw new Error(seleniumResult?.message ?? "BCBS MA session returned an error result");
  }

  log("bcbs-ma-processor", "processing DB result", { insuranceId });
  const result = await processBcbsMaResult(
    userId, insuranceId, formFirstName, formLastName, formDob, seleniumResult
  );

  log("bcbs-ma-processor", "done", { result });
  return result;
}
