/**
 * Imports data/medicines_with_price.csv (21,361 brands, 226 companies, auto-matched/created generics)
 * and uploads data/company-images-webp/ (2,169 .webp pack images) to Cloudflare R2 under brands/.
 *
 * Safe to re-run (idempotent): skips already-uploaded R2 images and upserts all DB rows in batches.
 *
 * Usage:
 *   npm run import-medicines:dev
 *   npm run import-medicines:dev -- --skip-r2
 */
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';
import { brandSlug, slugify } from '../lib/slug';

type FormIcon =
  | 'tablet'
  | 'capsule'
  | 'syrup'
  | 'suspension'
  | 'drops'
  | 'injection'
  | 'iv'
  | 'suppository'
  | 'cream'
  | 'powder';

function parseCSV(str: string): string[][] {
  const rows: string[][] = [];
  let row: string[] = [];
  let field = '';
  let inQ = false;
  for (let i = 0; i < str.length; i++) {
    const ch = str[i];
    if (inQ) {
      if (ch === '"' && str[i + 1] === '"') {
        field += '"';
        i++;
      } else if (ch === '"') {
        inQ = false;
      } else {
        field += ch;
      }
    } else {
      if (ch === '"') inQ = true;
      else if (ch === ',') {
        row.push(field);
        field = '';
      } else if (ch === '\n') {
        row.push(field.replace(/\r$/, ''));
        rows.push(row);
        row = [];
        field = '';
      } else {
        field += ch;
      }
    }
  }
  if (field || row.length) {
    row.push(field.replace(/\r$/, ''));
    rows.push(row);
  }
  return rows;
}

function parsePrice(raw: string | undefined): number | null {
  if (!raw) return null;
  const s = raw.trim();
  if (!s || /not found/i.test(s)) return null;
  const m = s.replace(/,/g, '').match(/(\d+(?:\.\d+)?)/);
  if (!m) return null;
  const n = Number(m[1]);
  if (!Number.isFinite(n) || n < 0 || n >= 1_000_000) return null;
  return Math.round(n * 100) / 100;
}

function parsePack(raw: string | undefined): { packLabel: string | null; packPrice: number | null } {
  if (!raw) return { packLabel: null, packPrice: null };
  const s = raw.trim();
  if (!s || /not found/i.test(s)) return { packLabel: null, packPrice: null };
  const first = s.split('|')[0].trim();
  const colonIdx = first.lastIndexOf(':');
  if (colonIdx > 0) {
    const label = first.slice(0, colonIdx).trim().slice(0, 120) || null;
    const price = parsePrice(first.slice(colonIdx + 1));
    return { packLabel: label, packPrice: price };
  }
  return { packLabel: first.slice(0, 120) || null, packPrice: null };
}

function inferIcon(form: string): FormIcon {
  const s = form.toLowerCase();
  if (/capsule|dpi|softgel|rotacap/.test(s)) return 'capsule';
  if (/suppos|pessar|enema|ovule|rectal|vaginal/.test(s)) return 'suppository';
  if (/infusion|dialysis|irrigation/.test(s)) return 'iv';
  if (/inject|vaccine|syringe|parenteral|implant/.test(s)) return 'injection';
  if (/suspension/.test(s)) return 'suspension';
  if (/syrup|elixir|linctus|mouthwash|gargle|oral solution/.test(s)) return 'syrup';
  if (/powder|sachet|granule|pellet|premix/.test(s)) return 'powder';
  if (/cream|ointment|gel|lotion|paste|shampoo|soap|foam|patch|liniment|balm/.test(s)) return 'cream';
  if (/drop|ophthalmic|otic|nasal|spray|aerosol|inhal|nebul|solution/.test(s)) return 'drops';
  return 'tablet';
}

const ROUTE_SUFFIX =
  /\s*\((oral|topical|injection|ophthalmic|inhalation|nasal|rectal|vaginal|otic|iv|im|sc|sublingual|pediatric|paediatric|adult|eye|ear|dental|buccal|parenteral|external|systemic)\)\s*$/i;

function creditForFolder(folder: string): string {
  const f = folder.toLowerCase();
  if (f.includes('beximco')) return 'Beximco Pharmaceuticals Ltd.';
  if (f.includes('incepta')) return 'Incepta Pharmaceuticals Ltd.';
  if (f.includes('renata')) return 'Renata Limited';
  if (f.includes('square')) return 'Square Pharmaceuticals Ltd.';
  return 'Manufacturer pack photo';
}

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;
}

function walkImages(dir: string): Array<{ full: string; filename: string; base: string; folder: string }> {
  const out: Array<{ full: string; filename: string; base: string; folder: string }> = [];
  const walk = (d: string) => {
    for (const e of fs.readdirSync(d, { withFileTypes: true })) {
      if (e.name.startsWith('.')) continue;
      const full = path.join(d, e.name);
      if (e.isDirectory()) walk(full);
      else if (/\.webp$/i.test(e.name)) {
        out.push({
          full,
          filename: e.name,
          base: path.parse(e.name).name.toLowerCase(),
          folder: path.basename(d),
        });
      }
    }
  };
  walk(dir);
  return out;
}

async function main() {
  const skipR2 = process.argv.includes('--skip-r2');
  const dataDir = path.resolve(__dirname, '../../../data');
  const csvPath = path.join(dataDir, 'medicines_with_price.csv');
  const imagesDir = path.join(dataDir, 'company-images-webp');

  if (!fs.existsSync(csvPath)) throw new Error(`Missing CSV: ${csvPath}`);
  const rawText = fs.readFileSync(csvPath, 'utf8').replace(/^\uFEFF/, '');
  const parsed = parseCSV(rawText).filter((r) => r.some((c) => c.trim() !== ''));
  const dataRows = parsed.slice(1);
  console.log(`Loaded ${dataRows.length} rows from medicines_with_price.csv.`);

  // 1. Upsert all companies
  const companyNameBySlug = new Map<string, string>();
  const companySlugByLower = new Map<string, string>();
  for (const r of dataRows) {
    const name = (r[5] ?? '').trim();
    if (!name) continue;
    const slug = slugify(name).slice(0, 140) || 'unknown-company';
    if (!companyNameBySlug.has(slug)) companyNameBySlug.set(slug, name.slice(0, 160));
    companySlugByLower.set(name.toLowerCase(), slug);
  }
  const companyRows = [...companyNameBySlug.entries()].map(([slug, name]) => ({
    slug,
    name,
    catalogues: 'human',
    status: 'published',
  }));
  for (let i = 0; i < companyRows.length; i += 100) {
    await db('companies')
      .insert(companyRows.slice(i, i + 100))
      .onConflict('slug')
      .merge(['name']);
  }
  const dbCompanies = (await db('companies').select('id', 'slug')) as Array<{ id: number | string; slug: string }>;
  const companyIdBySlug = new Map(dbCompanies.map((c) => [c.slug, Number(c.id)]));
  console.log(`✓ Upserted ${companyRows.length} companies.`);

  // 2. Smart-match existing generics + auto-create missing ones (pending)
  const dbGenerics = (await db('generics').select('id', 'slug', 'name')) as Array<{
    id: number | string;
    slug: string;
    name: string;
  }>;
  const genIdByLower = new Map<string, number>();
  const genIdBySlug = new Map<string, number>();
  for (const g of dbGenerics) {
    genIdByLower.set(g.name.trim().toLowerCase(), Number(g.id));
    genIdBySlug.set(g.slug, Number(g.id));
  }

  const newGenericsBySlug = new Map<string, { slug: string; name: string }>();
  let matchedByExact = 0;
  let matchedByStripped = 0;

  function resolveGenericSlugOrId(rawName: string): { id?: number; newSlug?: string } {
    const clean = rawName.trim();
    const lower = clean.toLowerCase();
    const direct = genIdByLower.get(lower);
    if (direct) {
      matchedByExact++;
      return { id: direct };
    }
    const stripped = clean.replace(ROUTE_SUFFIX, '').trim();
    const strippedId = genIdByLower.get(stripped.toLowerCase()) ?? genIdBySlug.get(slugify(stripped));
    if (strippedId) {
      matchedByStripped++;
      return { id: strippedId };
    }
    const baseName = stripped || clean;
    const baseSlug = slugify(baseName).slice(0, 155) || 'unknown-generic';
    const existingBySlug = genIdBySlug.get(baseSlug);
    if (existingBySlug) {
      matchedByStripped++;
      return { id: existingBySlug };
    }
    if (!newGenericsBySlug.has(baseSlug)) {
      newGenericsBySlug.set(baseSlug, { slug: baseSlug, name: baseName.slice(0, 160) });
    }
    return { newSlug: baseSlug };
  }

  // First pass: discover missing generics
  for (const r of dataRows) {
    const gName = (r[0] ?? '').trim();
    if (gName) resolveGenericSlugOrId(gName);
  }

  if (newGenericsBySlug.size > 0) {
    const newGenRows = [...newGenericsBySlug.values()].map((g) => ({
      slug: g.slug,
      name: g.name,
      catalogue: 'human',
      drug_class_id: null,
      status: 'published',
      review_status: 'pending',
      sources: JSON.stringify(['DGDA']),
    }));
    for (let i = 0; i < newGenRows.length; i += 100) {
      await db('generics')
        .insert(newGenRows.slice(i, i + 100))
        .onConflict('slug')
        .ignore();
    }
    const refreshed = (await db('generics').select('id', 'slug', 'name')) as Array<{
      id: number | string;
      slug: string;
      name: string;
    }>;
    for (const g of refreshed) {
      genIdByLower.set(g.name.trim().toLowerCase(), Number(g.id));
      genIdBySlug.set(g.slug, Number(g.id));
    }
  }
  console.log(
    `✓ Generics ready: ${matchedByExact} exact row matches, ${matchedByStripped} route-stripped matches, ${newGenericsBySlug.size} new pending generics created.`,
  );

  // 3. Load dosage forms lookup
  const dbForms = (await db('dosage_forms').select('id', 'name', 'icon', 'match_labels')) as Array<{
    id: number | string;
    name: string;
    icon: FormIcon;
    match_labels: string | string[];
  }>;
  const formByLower = new Map<string, { id: number; icon: FormIcon }>();
  for (const f of dbForms) {
    const labels: string[] = typeof f.match_labels === 'string' ? JSON.parse(f.match_labels) : f.match_labels;
    formByLower.set(f.name.trim().toLowerCase(), { id: Number(f.id), icon: f.icon });
    for (const lbl of labels) {
      formByLower.set(lbl.trim().toLowerCase(), { id: Number(f.id), icon: f.icon });
    }
  }

  // 4. Prepare & batch upsert all 21,361 brands
  const today = new Date().toISOString().slice(0, 10);
  const usedSlugs = new Set<string>();
  const pmToBrandSlugs = new Map<string, Array<{ slug: string; companySlug: string }>>();

  const brandRows: Array<Record<string, unknown>> = [];
  for (const r of dataRows) {
    const genericName = (r[0] ?? '').trim();
    const brandName = (r[1] ?? '').trim().slice(0, 120);
    const packageMark = (r[2] ?? '').trim().toLowerCase();
    const dosageType = (r[3] ?? '').trim().slice(0, 80) || 'Tablet';
    const strength = (r[4] ?? '').trim().slice(0, 80);
    const manufacturer = (r[5] ?? '').trim();
    const unitPrice = parsePrice(r[6]);
    const { packLabel, packPrice } = parsePack(r[7]);

    if (!brandName || !manufacturer) continue;

    const compSlug = companySlugByLower.get(manufacturer.toLowerCase()) ?? slugify(manufacturer).slice(0, 140);
    const companyId = companyIdBySlug.get(compSlug);
    if (!companyId) continue;

    const strippedGen = genericName.replace(ROUTE_SUFFIX, '').trim();
    const genericId =
      genIdByLower.get(genericName.toLowerCase()) ??
      genIdByLower.get(strippedGen.toLowerCase()) ??
      genIdBySlug.get(slugify(strippedGen).slice(0, 155)) ??
      null;

    const formMatch = formByLower.get(dosageType.toLowerCase());
    const formIcon: FormIcon = formMatch?.icon ?? inferIcon(dosageType);

    let slug = brandSlug(brandName, strength || 'std', dosageType).slice(0, 180);
    if (!slug) slug = slugify(`${brandName}-${dosageType}`).slice(0, 180) || 'brand';
    if (usedSlugs.has(slug)) {
      const withComp = `${slug.slice(0, 145)}-${compSlug.slice(0, 30)}`;
      if (!usedSlugs.has(withComp)) {
        slug = withComp;
      } else {
        let n = 2;
        while (usedSlugs.has(`${withComp.slice(0, 175)}-${n}`)) n++;
        slug = `${withComp.slice(0, 175)}-${n}`;
      }
    }
    usedSlugs.add(slug);

    if (packageMark) {
      if (!pmToBrandSlugs.has(packageMark)) pmToBrandSlugs.set(packageMark, []);
      pmToBrandSlugs.get(packageMark)!.push({ slug, companySlug: compSlug });
    }

    const famKey = `${slugify(brandName)}|${compSlug}|${slugify(dosageType)}`.slice(0, 190);
    brandRows.push({
      slug,
      name: brandName,
      generic_id: genericId,
      ingredient_label: genericId ? null : genericName.slice(0, 160) || null,
      company_id: companyId,
      catalogue: 'human',
      dosage_form_id: formMatch?.id ?? null,
      form_label: dosageType,
      form_icon: formIcon,
      strength,
      family_key: famKey,
      pack_label: packLabel,
      unit_price: unitPrice,
      pack_price: packPrice,
      price_updated_at: unitPrice !== null || packPrice !== null ? today : null,
      price_source: 'DGDA',
      status: 'published',
      added_at: today,
    });
  }

  console.log(`Upserting ${brandRows.length} brands in batches of 200…`);
  const BATCH = 200;
  for (let i = 0; i < brandRows.length; i += BATCH) {
    await db('brands')
      .insert(brandRows.slice(i, i + BATCH))
      .onConflict('slug')
      .merge([
        'name',
        'generic_id',
        'ingredient_label',
        'company_id',
        'dosage_form_id',
        'form_label',
        'form_icon',
        'strength',
        'family_key',
        'pack_label',
        'unit_price',
        'pack_price',
        'price_updated_at',
      ]);
    const done = Math.min(i + BATCH, brandRows.length);
    if (done % 2000 === 0 || done === brandRows.length) {
      console.log(`  Brands progress: ${done}/${brandRows.length}…`);
    }
  }
  console.log(`✓ Upserted ${brandRows.length} brands.`);

  // 5. Upload 2,169 images to R2 under brands/
  const imgFiles = walkImages(imagesDir);
  const { publicUrl } = r2();

  if (!skipR2) {
    console.log(`Checking existing R2 objects under brands/ …`);
    const existingR2 = await listExistingR2Keys('brands/');
    const pending = imgFiles.filter((f) => !existingR2.has(`brands/${f.filename}`));
    console.log(
      `R2 brand images: ${imgFiles.length} total, ${imgFiles.length - pending.length} already in R2, ${pending.length} to upload.`,
    );

    const CONCURRENCY = 20;
    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.full);
          await putObject(`brands/${item.filename}`, buf, 'image/webp');
          uploaded++;
          if (uploaded % 200 === 0 || uploaded === pending.length) {
            console.log(`  Uploaded ${uploaded}/${pending.length} brand images to R2…`);
          }
        } catch (err) {
          failed++;
          const msg = err instanceof Error ? err.message : String(err);
          if (failed <= 5) console.error(`  ✗ Failed brands/${item.filename}: ${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} brand image uploads failed.`);
    console.log(`✓ R2 brand image sync complete (${imgFiles.length} images ready).`);
  }

  // 6. Upsert images table + link brand_images
  const imageRows = imgFiles.map((f) => {
    const key = `brands/${f.filename}`;
    const stat = fs.statSync(f.full);
    return {
      r2_key: key,
      url: `${publicUrl}/${key}`,
      mime: 'image/webp',
      size_bytes: stat.size,
      credit: creditForFolder(f.folder),
      photo_date: today,
      status: 'published',
    };
  });
  for (let i = 0; i < imageRows.length; i += 200) {
    await db('images')
      .insert(imageRows.slice(i, i + 200))
      .onConflict('r2_key')
      .merge(['url', 'size_bytes', 'credit']);
  }

  const dbImages = (await db('images').select('id', 'r2_key').where('r2_key', 'like', 'brands/%')) as Array<{
    id: number | string;
    r2_key: string;
  }>;
  const imgIdByKey = new Map(dbImages.map((x) => [x.r2_key, Number(x.id)]));

  const dbBrands = (await db('brands').select('id', 'slug')) as Array<{ id: number | string; slug: string }>;
  const brandIdBySlug = new Map(dbBrands.map((b) => [b.slug, Number(b.id)]));

  const brandImageRows: Array<{ brand_id: number; image_id: number; side: 'front' | 'back'; sort_order: number }> = [];
  const seenLink = new Set<string>();
  const hasFront = new Set<number>();

  // Sort images so base files (without _N) come before _1, _2, ...
  const sortedImgs = [...imgFiles].sort((a, b) => {
    const ma = a.base.match(/_(\d+)$/);
    const mb = b.base.match(/_(\d+)$/);
    const na = ma ? Number(ma[1]) : 0;
    const nb = mb ? Number(mb[1]) : 0;
    return na - nb;
  });

  for (const f of sortedImgs) {
    const imgId = imgIdByKey.get(`brands/${f.filename}`);
    if (!imgId) continue;
    const suffixMatch = f.base.match(/_(\d+)$/);
    const pmKey = suffixMatch ? f.base.replace(/_\d+$/, '') : f.base;
    const sortOrder = suffixMatch ? Number(suffixMatch[1]) : 0;
    const targets = pmToBrandSlugs.get(f.base) ?? pmToBrandSlugs.get(pmKey);
    if (!targets || !targets.length) continue;

    // If multiple brands share the packageMark, prefer the one matching the folder's company
    const folderKey = f.folder.split('_')[0].toLowerCase();
    const matched = targets.filter((t) => t.companySlug.includes(folderKey));
    const chosen = matched.length ? matched : targets;

    for (const t of chosen) {
      const brandId = brandIdBySlug.get(t.slug);
      if (!brandId) continue;
      const lk = `${brandId}:${imgId}`;
      if (seenLink.has(lk)) continue;
      seenLink.add(lk);
      const side: 'front' | 'back' = !hasFront.has(brandId) ? 'front' : 'back';
      if (side === 'front') hasFront.add(brandId);
      brandImageRows.push({ brand_id: brandId, image_id: imgId, side, sort_order: sortOrder });
    }
  }

  for (let i = 0; i < brandImageRows.length; i += 300) {
    await db('brand_images')
      .insert(brandImageRows.slice(i, i + 300))
      .onConflict(['brand_id', 'image_id'])
      .merge(['side', 'sort_order']);
  }

  const [[summary]] = (await db.raw(`
    SELECT
      (SELECT COUNT(*) FROM companies) AS companies,
      (SELECT COUNT(*) FROM generics) AS generics,
      (SELECT COUNT(*) FROM brands) AS brands,
      (SELECT COUNT(*) FROM images) AS images,
      (SELECT COUNT(*) FROM brand_images) AS brand_images,
      (SELECT COUNT(DISTINCT brand_id) FROM brand_images) AS brands_with_images
  `)) as [[Record<string, number>]];

  console.log('✓ ALL DONE! DB Summary:', summary);
}

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