/**
 * Imports top-1374-complete.json generics into MySQL and uploads chemical structure
 * images from data-pipeline/output/images/ to Cloudflare R2 under generics/<slug>-structure.webp.
 *
 * Safe to re-run (idempotent): skips already-uploaded R2 images and upserts generics by slug.
 *
 * Usage:
 *   npm run import-generics:dev
 *   npm run import-generics:dev -- --skip-r2   (DB only, still sets R2 URLs)
 */
import fs from 'node:fs';
import path from 'node:path';
import { ListObjectsV2Command } from '@aws-sdk/client-s3';
import { db } from '../db/knex';
import { putObject, r2 } from '../lib/r2';

type LangVal = { en?: string | null; bn?: string | null };
type RawGeneric = {
  slug: string;
  name: string;
  therapeuticClass?: LangVal | null;
  prescriptionRequired?: boolean | null;
  foodTiming?: 'before' | 'after' | 'with' | 'any' | null;
  quickSummary?: {
    usedFor?: LangVal | null;
    usualAdultDose?: LangVal | null;
    howToTake?: LangVal | null;
    keySafetyNote?: LangVal | null;
  } | null;
  chemicalInfo?: {
    pubchemCid?: number | null;
    molecularFormula?: string | null;
    molecularWeight?: string | null;
    iupacName?: string | null;
    structureImage?: string | null;
    pubchemUrl?: string | null;
  } | null;
  sections?: Record<string, LangVal | undefined> | null;
  faq?: Array<{ q?: LangVal; a?: LangVal }> | null;
  sources?: Array<string | { name?: string }> | null;
  drugClassSlug?: string | null;
};

const JSON_SECTION_TO_DB: Record<string, string> = {
  indications: 'indications',
  dosage: 'dosage',
  sideEffects: 'side_effects',
  precautionsAndWarnings: 'precautions',
  pregnancyAndLactation: 'pregnancy',
  contraindications: 'contraindications',
  interactions: 'interactions',
  pharmacology: 'pharmacology',
  overdose: 'overdose',
  storage: 'storage',
  specialPopulations: 'special_populations',
  patientCounseling: 'patient_counseling',
};

const VET_REGEX = /veterinary|vet only|not for human/i;
const trim = (v: unknown, max?: number) => {
  const s = typeof v === 'string' ? v.trim() : '';
  if (!s) return null;
  return max && s.length > max ? s.slice(0, max) : s;
};

async function listExistingR2Keys(prefix: string): Promise<Set<string>> {
  const { client, bucket } = r2();
  const keys = new Set<string>();
  let token: string | undefined;
  do {
    const res = await client.send(
      new ListObjectsV2Command({ Bucket: bucket, Prefix: prefix, ContinuationToken: token }),
    );
    for (const obj of res.Contents ?? []) {
      if (obj.Key) keys.add(obj.Key);
    }
    token = res.IsTruncated ? res.NextContinuationToken : undefined;
  } while (token);
  return keys;
}

async function uploadImagesToR2(
  items: RawGeneric[],
  imagesDir: string,
  skipR2: boolean,
): Promise<Map<string, string>> {
  const { publicUrl } = r2();
  const urlBySlug = new Map<string, string>();
  const toUpload: Array<{ slug: string; key: string; filePath: string }> = [];

  for (const g of items) {
    const rel = g.chemicalInfo?.structureImage;
    if (!rel) continue;
    const fname = path.basename(rel);
    const filePath = path.join(imagesDir, fname);
    if (!fs.existsSync(filePath)) continue;
    const key = `generics/${fname}`;
    urlBySlug.set(g.slug, `${publicUrl}/${key}`);
    toUpload.push({ slug: g.slug, key, filePath });
  }

  if (skipR2) {
    console.log(`Skipping R2 upload (--skip-r2). Mapped ${urlBySlug.size} image URLs.`);
    return urlBySlug;
  }

  console.log(`Checking existing R2 objects under generics/ …`);
  const existing = await listExistingR2Keys('generics/');
  const pending = toUpload.filter((x) => !existing.has(x.key));
  console.log(
    `R2 images: ${toUpload.length} total, ${toUpload.length - pending.length} already in R2, ${pending.length} to upload.`,
  );

  const CONCURRENCY = 15;
  let uploaded = 0;
  let failed = 0;
  let aborted = false;
  let idx = 0;

  async function worker() {
    while (idx < pending.length && !aborted) {
      const item = pending[idx++];
      try {
        const buf = fs.readFileSync(item.filePath);
        await putObject(item.key, buf, 'image/webp');
        uploaded++;
        if (uploaded % 100 === 0 || uploaded === pending.length) {
          console.log(`  Uploaded ${uploaded}/${pending.length} images to R2…`);
        }
      } catch (err) {
        failed++;
        const msg = err instanceof Error ? err.message : String(err);
        if (failed <= 5) console.error(`  ✗ Failed ${item.key}: ${msg}`);
        if (/Access Denied|SignatureDoesNotMatch|InvalidAccessKeyId/i.test(msg)) {
          aborted = true;
          return;
        }
      }
    }
  }

  await Promise.all(Array.from({ length: Math.min(CONCURRENCY, pending.length) }, () => worker()));
  if (failed > 0) {
    throw new Error(`${failed} image uploads failed. Re-run to retry only the failed ones.`);
  }
  console.log(`✓ R2 image sync complete (${urlBySlug.size} images ready).`);
  return urlBySlug;
}

async function importGenericsToDb(items: RawGeneric[], urlBySlug: Map<string, string>) {
  const dbClasses = (await db('drug_classes').select('id', 'slug')) as Array<{ id: number | string; slug: string }>;
  const classIdBySlug = new Map(dbClasses.map((c) => [c.slug, Number(c.id)]));
  const defaultRev = (await db('reviewers').select('id', 'name').where({ slug: 'bdmedicine-editorial' }).first()) as
    | { id: number | string; name: string }
    | undefined;
  const today = new Date().toISOString().slice(0, 10);

  const BATCH = 50;
  let inserted = 0;
  let updated = 0;
  let totalSections = 0;

  for (let i = 0; i < items.length; i += BATCH) {
    const chunk = items.slice(i, i + BATCH);
    await db.transaction(async (trx) => {
      const slugs = chunk.map((g) => g.slug);
      const existingRows = await trx('generics')
        .select('id', 'slug', 'review_status', 'drug_class_id')
        .whereIn('slug', slugs);
      const existingBySlug = new Map(
        existingRows.map(
          (r: { id: number | string; slug: string; review_status: string; drug_class_id: number | null }) => [
            r.slug,
            r,
          ],
        ),
      );

      const batchGenericIds: Array<number | string> = [];
      const batchSectionRows: Array<{
        generic_id: number | string;
        section: string;
        body_en: string;
        body_bn: string | null;
      }> = [];

      for (const g of chunk) {
        const existing = existingBySlug.get(g.slug);
        const classEn = trim(g.therapeuticClass?.en, 160);
        const classBn = trim(g.therapeuticClass?.bn, 200);
        const catalogue = VET_REGEX.test(g.therapeuticClass?.en ?? '') ? 'vet' : 'human';
        const matchedClassId = g.drugClassSlug ? (classIdBySlug.get(g.drugClassSlug.trim()) ?? null) : null;
        const sources = Array.from(
          new Set(
            (g.sources ?? [])
              .map((s) => (typeof s === 'string' ? s.trim() : (s?.name ?? '').trim()))
              .filter(Boolean),
          ),
        );
        const chemicalInfo = g.chemicalInfo
          ? {
              pubchemCid: g.chemicalInfo.pubchemCid ?? null,
              molecularFormula: trim(g.chemicalInfo.molecularFormula, 120),
              molecularWeight: trim(g.chemicalInfo.molecularWeight, 60),
              iupacName: trim(g.chemicalInfo.iupacName, 600),
              pubchemUrl: trim(g.chemicalInfo.pubchemUrl, 500),
            }
          : null;
        const faq = (g.faq ?? [])
          .map((item) => ({
            q: { en: trim(item.q?.en) ?? '', ...(trim(item.q?.bn) ? { bn: trim(item.q?.bn)! } : {}) },
            a: { en: trim(item.a?.en) ?? '', ...(trim(item.a?.bn) ? { bn: trim(item.a?.bn)! } : {}) },
          }))
          .filter((f) => f.q.en || f.a.en);

        const row = {
          slug: g.slug,
          name: trim(g.name, 160) ?? g.slug,
          catalogue,
          ...(matchedClassId ? { drug_class_id: matchedClassId } : {}),
          class_label: classEn,
          class_label_bn: classBn,
          tagline: trim(g.therapeuticClass?.en, 120),
          ...(urlBySlug.get(g.slug) ? { structure_image_url: urlBySlug.get(g.slug) } : {}),
          ...(chemicalInfo ? { chemical_info: JSON.stringify(chemicalInfo) } : {}),
          faq: faq.length ? JSON.stringify(faq) : null,
          sources: JSON.stringify(sources.length ? sources : ['DGDA']),
          summary_use_en: trim(g.quickSummary?.usedFor?.en),
          summary_use_bn: trim(g.quickSummary?.usedFor?.bn),
          summary_dose_en: trim(g.quickSummary?.usualAdultDose?.en),
          summary_dose_bn: trim(g.quickSummary?.usualAdultDose?.bn),
          summary_how_to_take_en: trim(g.quickSummary?.howToTake?.en),
          summary_how_to_take_bn: trim(g.quickSummary?.howToTake?.bn),
          summary_safety_en: trim(g.quickSummary?.keySafetyNote?.en),
          summary_safety_bn: trim(g.quickSummary?.keySafetyNote?.bn),
          food_timing: g.foodTiming ?? null,
          prescription:
            typeof g.prescriptionRequired === 'boolean'
              ? g.prescriptionRequired
                ? 'required'
                : 'not_required'
              : null,
        };

        let genericId: number | string;
        if (existing) {
          await trx('generics').where({ id: existing.id }).update(row);
          genericId = existing.id;
          updated++;
        } else {
          const [id] = await trx('generics').insert({
            ...row,
            drug_class_id: matchedClassId,
            status: 'published',
            review_status: 'approved',
            reviewer_id: defaultRev?.id ?? null,
            reviewer_name: defaultRev?.name ?? null,
            reviewed_at: today,
          });
          genericId = id;
          inserted++;
        }

        batchGenericIds.push(genericId);
        for (const [jsonKey, dbSection] of Object.entries(JSON_SECTION_TO_DB)) {
          const val = g.sections?.[jsonKey];
          const en = trim(val?.en) ?? '';
          const bn = trim(val?.bn);
          if (en || bn) {
            batchSectionRows.push({ generic_id: genericId, section: dbSection, body_en: en, body_bn: bn });
          }
        }
      }

      if (batchGenericIds.length) {
        await trx('generic_info').whereIn('generic_id', batchGenericIds).del();
      }
      for (let j = 0; j < batchSectionRows.length; j += 200) {
        await trx('generic_info').insert(batchSectionRows.slice(j, j + 200));
      }
      totalSections += batchSectionRows.length;
    });

    const done = Math.min(i + BATCH, items.length);
    console.log(`  DB progress: ${done}/${items.length} generics (inserted: ${inserted}, updated: ${updated})…`);
  }

  console.log(
    `✓ DB import complete: ${inserted} inserted, ${updated} updated, ${totalSections} section rows written.`,
  );
}

async function main() {
  const skipR2 = process.argv.includes('--skip-r2');
  const fileIdx = process.argv.indexOf('--file');
  const customFile = fileIdx >= 0 ? process.argv[fileIdx + 1] : undefined;
  const pipelineDir = path.resolve(__dirname, '../../../data-pipeline/output');
  const jsonPath = customFile
    ? path.isAbsolute(customFile)
      ? customFile
      : path.resolve(pipelineDir, customFile)
    : path.join(pipelineDir, 'top-1374-complete.json');
  const imagesDir = path.join(pipelineDir, 'images');

  if (!fs.existsSync(jsonPath)) {
    throw new Error(`Missing dataset: ${jsonPath}`);
  }

  const parsed = JSON.parse(fs.readFileSync(jsonPath, 'utf8')) as RawGeneric[] | { generics: RawGeneric[] };
  const items = Array.isArray(parsed) ? parsed : parsed.generics;
  console.log(`Loaded ${items.length} generics from ${path.basename(jsonPath)}.`);

  const urlBySlug = await uploadImagesToR2(items, imagesDir, skipR2);
  await importGenericsToDb(items, urlBySlug);
}

main()
  .catch((err) => {
    console.error('✗ Import failed:', err instanceof Error ? err.message : err);
    process.exitCode = 1;
  })
  .finally(() => db.destroy());
