// Post-processing: compute real transit info from Amap and store in plan

import { getTransitDirection } from "@/lib/amap";

async function queryTransit(
  oLng: number,
  oLat: number,
  dLng: number,
  dLat: number,
  city: string,
): Promise<{ durationMin: number; description: string } | null> {
  try {
    const result = await getTransitDirection({
      originLat: oLat,
      originLng: oLng,
      destLat: dLat,
      destLng: dLng,
      city,
    });
    if (!result) return null;
    return { durationMin: result.durationMin, description: result.description };
  } catch (e) {
    console.error("queryTransit failed:", e);
    return null;
  }
}

export type EnrichDay = {
  date: string;
  items: Record<string, unknown>[];
  summary: string;
  transitFromStart?: number;
  transitFromStartDescription?: string;
  transitToEnd?: number;
  transitToEndDescription?: string;
};

export async function enrichTransitInfo(
  days: EnrichDay[],
  city: string,
  homeLat: number,
  homeLng: number,
): Promise<void> {
  const cityParam = city || "上海";

  for (const day of days) {
    const items = day.items;

    // From home to first activity
    if (items.length > 0 && homeLat && homeLng) {
      const dLat = Number(items[0].lat);
      const dLng = Number(items[0].lng);
      if (dLat && dLng) {
        const result = await queryTransit(homeLng, homeLat, dLng, dLat, cityParam);
        if (result) {
          day.transitFromStart = result.durationMin;
          day.transitFromStartDescription = result.description;
        }
      }
    }

    // Between consecutive activities
    for (let i = 0; i < items.length - 1; i++) {
      const oLat = Number(items[i].lat);
      const oLng = Number(items[i].lng);
      const dLat = Number(items[i + 1].lat);
      const dLng = Number(items[i + 1].lng);
      if (!oLat || !oLng || !dLat || !dLng) continue;
      const result = await queryTransit(oLng, oLat, dLng, dLat, cityParam);
      if (result) {
        items[i].transitToNext = result.durationMin;
        items[i].transitDescription = result.description;
      }
    }

    // From last activity back home
    if (items.length > 0 && homeLat && homeLng) {
      const last = items[items.length - 1];
      const oLat = Number(last.lat);
      const oLng = Number(last.lng);
      if (oLat && oLng) {
        const result = await queryTransit(oLng, oLat, homeLng, homeLat, cityParam);
        if (result) {
          day.transitToEnd = result.durationMin;
          day.transitToEndDescription = result.description;
        }
      }
    }
  }
}
