import { prisma } from '../src/lib/prisma.js';

const parseArgs = () => {
  const args = process.argv.slice(2);
  const flags = new Set(args);
  return {
    apply: flags.has('--apply'),
    createMissing: flags.has('--create-missing'),
    limit: (() => {
      const idx = args.findIndex((x) => x === '--limit');
      if (idx === -1) return undefined;
      const raw = args[idx + 1];
      const n = Number(raw);
      return Number.isFinite(n) && n > 0 ? n : undefined;
    })(),
  };
};

const normalize = (s: string) =>
  s
    .trim()
    .toLowerCase()
    .replace(/[_\-]+/g, ' ')
    .replace(/[^a-z0-9\s]/g, '')
    .replace(/\s+/g, ' ')
    .trim();

const main = async () => {
  const { apply, createMissing, limit } = parseArgs();

  if (!apply && createMissing) {
    throw new Error('Refusing to create missing catalog rows without --apply. Use --apply --create-missing');
  }

  const [regions, cities] = await Promise.all([
    (prisma as any).catalogRegion.findMany({
      select: { id: true, name: true },
    }),
    (prisma as any).catalogCity.findMany({
      select: { id: true, name: true, regionId: true, region: { select: { name: true } } },
    }),
  ]);

  const regionById = new Map<string, { id: string; name: string }>();
  const regionByNormName = new Map<string, { id: string; name: string }>();
  for (const r of regions as any[]) {
    const id = String(r.id);
    const name = String(r.name);
    regionById.set(id, { id, name });
    regionByNormName.set(normalize(name), { id, name });
  }

  const cityById = new Map<string, { id: string; name: string; regionId: string; regionName: string }>();
  const citiesByNormName = new Map<string, Array<{ id: string; name: string; regionId: string; regionName: string }>>();
  for (const c of cities as any[]) {
    const row = {
      id: String(c.id),
      name: String(c.name),
      regionId: String(c.regionId),
      regionName: String(c.region?.name || ''),
    };
    cityById.set(row.id, row);
    const k = normalize(row.name);
    const arr = citiesByNormName.get(k) || [];
    arr.push(row);
    citiesByNormName.set(k, arr);
  }

  const rows = await (prisma as any).property.findMany({
    where: {
      OR: [
        { regionId: null },
        { cityId: null },
        { state: null },
        { city: '' },
        { subCityId: null, subCity: { not: null } },
      ],
    },
    select: {
      id: true,
      subCity: true,
      subCityId: true,
      city: true,
      cityId: true,
      state: true,
      regionId: true,
    },
    take: limit ?? 5000,
  });

  let updated = 0;
  let skipped = 0;
  let created = 0;
  let createdRegions = 0;
  let createdCities = 0;
  let wouldUpdate = 0;

  let skippedMissingCity = 0;
  let skippedAmbiguousCity = 0;
  const unmatchedSamples: Array<{ state: string; city: string; subCity: string }> = [];

  const subCityCacheByCityId = new Map<string, Map<string, { id: string; name: string; cityId: string }>>();

  for (const p of rows as any[]) {
    const cityNameRaw = String(p.city || '').trim();
    const regionNameRaw = String(p.state || '').trim();
    const subCityNameRaw = String(p.subCity || '').trim();

    const propertyCityId = p.cityId ? String(p.cityId) : '';
    const propertyRegionId = p.regionId ? String(p.regionId) : '';
    const propertySubCityId = p.subCityId ? String(p.subCityId) : '';

    let regionRow: { id: string; name: string } | null = null;
    if (propertyRegionId && regionById.has(propertyRegionId)) {
      regionRow = regionById.get(propertyRegionId) || null;
    } else if (regionNameRaw) {
      regionRow = regionByNormName.get(normalize(regionNameRaw)) || null;
    }

    if (!regionRow && apply && createMissing && regionNameRaw) {
      const existing = regionByNormName.get(normalize(regionNameRaw)) || null;
      if (existing) {
        regionRow = existing;
      } else {
        const createdRegion = await (prisma as any).catalogRegion.create({
          data: {
            name: regionNameRaw,
            enabled: true,
            sortOrder: 0,
          },
          select: { id: true, name: true },
        });
        const newRegion = { id: String(createdRegion.id), name: String(createdRegion.name) };
        regionById.set(newRegion.id, newRegion);
        regionByNormName.set(normalize(newRegion.name), newRegion);
        regionRow = newRegion;
        createdRegions++;
      }
    }

    let cityRow: { id: string; name: string; regionId: string; regionName: string } | null = null;
    if (propertyCityId && cityById.has(propertyCityId)) {
      cityRow = cityById.get(propertyCityId) || null;
    } else if (cityNameRaw) {
      const candidates = citiesByNormName.get(normalize(cityNameRaw)) || [];
      if (candidates.length === 1) {
        cityRow = candidates[0];
      } else if (candidates.length > 1) {
        const byRegion = regionRow ? candidates.filter((c) => c.regionId === regionRow!.id) : [];
        if (byRegion.length === 1) cityRow = byRegion[0];
      }
    }

    if (!cityRow && cityNameRaw) {
      const key = normalize(cityNameRaw);
      if (key) {
        const fuzzy: Array<{ id: string; name: string; regionId: string; regionName: string }> = [];
        for (const c of cities as any[]) {
          const candKey = normalize(String(c.name || ''));
          if (!candKey) continue;
          if (candKey === key || candKey.includes(key) || key.includes(candKey)) {
            fuzzy.push({
              id: String(c.id),
              name: String(c.name),
              regionId: String(c.regionId),
              regionName: String(c.region?.name || ''),
            });
          }
        }
        if (fuzzy.length === 1) {
          cityRow = fuzzy[0];
        } else if (fuzzy.length > 1) {
          const byRegion = regionRow ? fuzzy.filter((c) => c.regionId === regionRow!.id) : [];
          if (byRegion.length === 1) {
            cityRow = byRegion[0];
          } else {
            skippedAmbiguousCity++;
          }
        }
      }
    }

    if (!cityRow && apply && createMissing && cityNameRaw) {
      if (!regionRow && regionNameRaw) {
        const existingRegion = regionByNormName.get(normalize(regionNameRaw)) || null;
        if (existingRegion) {
          regionRow = existingRegion;
        } else {
          const createdRegion = await (prisma as any).catalogRegion.create({
            data: {
              name: regionNameRaw,
              enabled: true,
              sortOrder: 0,
            },
            select: { id: true, name: true },
          });
          const newRegion = { id: String(createdRegion.id), name: String(createdRegion.name) };
          regionById.set(newRegion.id, newRegion);
          regionByNormName.set(normalize(newRegion.name), newRegion);
          regionRow = newRegion;
          createdRegions++;
        }
      }

      if (regionRow) {
        const createdCity = await (prisma as any).catalogCity.create({
          data: {
            regionId: regionRow.id,
            name: cityNameRaw,
            enabled: true,
            sortOrder: 0,
          },
          select: { id: true, name: true, regionId: true },
        });
        const createdCityRow = {
          id: String(createdCity.id),
          name: String(createdCity.name),
          regionId: String(createdCity.regionId),
          regionName: regionRow.name,
        };
        cityById.set(createdCityRow.id, createdCityRow);
        const k = normalize(createdCityRow.name);
        const arr = citiesByNormName.get(k) || [];
        arr.push(createdCityRow);
        citiesByNormName.set(k, arr);
        cityRow = createdCityRow;
        createdCities++;
      }
    }

    if (!cityRow?.id) {
      skippedMissingCity++;
      if (unmatchedSamples.length < 25) {
        unmatchedSamples.push({ state: regionNameRaw, city: cityNameRaw, subCity: subCityNameRaw });
      }
      skipped++;
      continue;
    }

    if (!regionRow) {
      regionRow = regionById.get(cityRow.regionId) || null;
    }

    let subCityRow: { id: string; name: string; cityId: string } | null = null;

    if (propertySubCityId) {
      const sc = await (prisma as any).catalogSubCity.findUnique({
        where: { id: propertySubCityId },
        select: { id: true, name: true, cityId: true },
      });
      if (sc?.id) {
        subCityRow = { id: String(sc.id), name: String(sc.name), cityId: String(sc.cityId) };
      }
    }

    if (!subCityRow && subCityNameRaw) {
      let cityCache = subCityCacheByCityId.get(cityRow.id) || null;
      if (!cityCache) {
        const subCities = await (prisma as any).catalogSubCity.findMany({
          where: { cityId: cityRow.id },
          select: { id: true, name: true, cityId: true },
        });
        cityCache = new Map();
        for (const sc of subCities as any[]) {
          cityCache.set(normalize(String(sc.name)), {
            id: String(sc.id),
            name: String(sc.name),
            cityId: String(sc.cityId),
          });
        }
        subCityCacheByCityId.set(cityRow.id, cityCache);
      }

      const found = cityCache.get(normalize(subCityNameRaw)) || null;
      if (found) {
        subCityRow = found;
      } else if (createMissing) {
        const createdRow = await (prisma as any).catalogSubCity.create({
          data: {
            cityId: cityRow.id,
            name: subCityNameRaw,
            enabled: true,
            sortOrder: 0,
          },
          select: { id: true, name: true, cityId: true },
        });
        created++;
        subCityRow = { id: String(createdRow.id), name: String(createdRow.name), cityId: String(createdRow.cityId) };
        cityCache.set(normalize(subCityRow.name), subCityRow);
      }
    }

    const updateData: any = {};

    if (!propertyCityId || propertyCityId !== cityRow.id) updateData.cityId = cityRow.id;
    if (cityRow.name && String(p.city || '') !== cityRow.name) updateData.city = cityRow.name;

    if (regionRow?.id) {
      if (!propertyRegionId || propertyRegionId !== regionRow.id) updateData.regionId = regionRow.id;
      if (regionRow.name && String(p.state || '') !== regionRow.name) updateData.state = regionRow.name;
    }

    if (subCityRow?.id) {
      if (!propertySubCityId || propertySubCityId !== subCityRow.id) updateData.subCityId = subCityRow.id;
      if (subCityRow.name && String(p.subCity || '') !== subCityRow.name) updateData.subCity = subCityRow.name;
    }

    if (Object.keys(updateData).length === 0) {
      skipped++;
      continue;
    }

    if (apply) {
      await (prisma as any).property.update({ where: { id: p.id }, data: updateData });
      updated++;
    } else {
      wouldUpdate++;
    }
  }

  console.log(
    JSON.stringify(
      {
        scanned: rows.length,
        updated,
        wouldUpdate,
        skipped,
        skippedMissingCity,
        skippedAmbiguousCity,
        unmatchedSamples,
        createdCatalogSubCities: created,
        createdCatalogCities: createdCities,
        createdCatalogRegions: createdRegions,
        mode: apply ? 'apply' : 'dry-run',
      },
      null,
      2,
    ),
  );
};

main()
  .catch((e) => {
    console.error(e);
    process.exitCode = 1;
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
