/* SkyOps — referential integrity pass. Runs once at load, after all stores exist, before App renders.
   Links seed inspections to fleet drones + crew, fills missing baselines, normalises WO assignees,
   and derives site last/next inspection + open criticals from the inspection record. */
(() => {
  try { const ed = JSON.parse(localStorage.getItem("skyops_site_edits") || "{}"); (window.SITES || []).forEach(s => { if (ed[s.id]) Object.assign(s, ed[s.id]); }); } catch {}
  const I = window.INSPECTIONS || [], S = window.SITES || [], R = window.resStore, W = window.woStore;

  // 1. Missing baseline referenced by Albacete + WO-2026-0388
  if (!I.find(i => i.id === "MIC-2026-01-011")) I.push({
    id: "MIC-2026-01-011", siteId: "es-ab-01", cycle: "Q1 2026", status: "closed", startedAt: "2026-01-12", plannedFor: "2026-01-12", baseline: null,
    coverage: 97.2, detections: 612, critical: 4, lead: "A. Soler", drone: "SKY-D04 · DJI Mavic 3T · Integrated",
    progress: { draft: 1, scheduled: 1, flying: 1, processing: 1, review: 1, reported: 1, closed: 1 },
    flights: 9, images: 2980, bytes: 398_000_000_000, gsd: 1.5, area_ha: 260.0,
  });

  if (!I.find(i => i.id === "MIC-2025-10-006")) I.push({
    id: "MIC-2025-10-006", siteId: "es-mu-02", cycle: "Q4 2025", status: "closed", startedAt: "2025-10-14", plannedFor: "2025-10-14", baseline: null,
    coverage: 98.6, detections: 342, critical: 9, lead: "M. Rivera", drone: "SKY-D02",
    progress: { draft: 1, scheduled: 1, flying: 1, processing: 1, review: 1, reported: 1, closed: 1 },
    flights: 5, images: 1290, bytes: 104_600_000_000, gsd: 1.8, area_ha: 82.1,
  });
  // Any baseline that still points nowhere is cleared
  I.forEach(i => { if (i.baseline && !I.find(x => x.id === i.baseline)) i.baseline = null; });

  // Legacy state: flown without start date, processed without results
  I.forEach(i => {
    const p = i.progress || {};
    if (p.flying > 0 && !i.startedAt && i.plannedFor) i.startedAt = i.plannedFor;
    if (p.processing >= 1 && !i.detections) {
      const ha = i.area_ha || 100; i.detections = Math.round(ha * 2.9); i.critical = Math.max(1, Math.round(i.detections * 0.025));
      i.coverage = i.coverage || 97.6; i.gsd = i.gsd || 1.3;
    }
    if (i.startedAt !== undefined && window.saveMicState && /^MIC-2026-(0[5-9]|1)/.test(i.id) && p.flying > 0) window.saveMicState(i);
  });

  // 2. Crew: A. Soler leads Albacete inspections
  if (R && !R.data.people.find(p => p.name === "A. Soler")) {
    R.data.people.push({ id: "P-" + String(R.data.people.length + 1).padStart(2, "0"), name: "A. Soler", role: "Pilot · thermographer", kind: "employee", org: "Iberdrola O&M", region: "Castilla-La Mancha", phone: "+34 622 118 407", rate: null,
      certs: [["EASA A2 CofC", "2027-02-18"], ["Thermography Level 2", "2027-03-30"]], skills: ["Pilot", "Thermography"], status: "available" });
  }

  // 3. Seed inspections → fleet drone labels
  if (R) {
    const byId = Object.fromEntries(R.data.drones.map(d => [d.id, window.droneLabel(d)]));
    const SITE_DRONE = { "pt-ev-03": "SKY-D01", "es-mu-02": "SKY-D02", "es-zr-07": "ASI-07", "es-ab-01": "SKY-D04" };
    I.forEach(i => {
      if (i.drone && /^(SKY|ASI)-\w+ · /.test(i.drone)) return;
      if (i.drone && byId[i.drone]) { i.drone = byId[i.drone]; return; }
      const id = i.drone === "DJI M300 RTK" ? "SKY-D03" : SITE_DRONE[i.siteId];
      if (id && byId[id]) i.drone = byId[id];
    });
  }

  // 4. WO assignees must match a crew label exactly (case-insensitive repair)
  if (W && R) {
    const labels = [...R.data.people.map(window.resLabel), ...R.data.companies.map(window.resLabel)];
    let changed = false;
    const list = W.list.map(w => {
      if (!w.assignee || w.assignee === "Unassigned" || labels.includes(w.assignee)) return w;
      const fix = labels.find(l => l.toLowerCase() === w.assignee.toLowerCase()) || labels.find(l => l.split(" · ")[0] === w.assignee.split(" · ")[0]);
      if (fix) { changed = true; return { ...w, assignee: fix }; }
      return w;
    });
    if (changed) W.set(() => list);
  }

  // 4b. Single timeline: stores seeded with autumn dates are shifted to the data era (once)
  if (!localStorage.getItem("skyops_dates_v2")) {
    const sh = (s) => s.replace(/\b2026-(09|1[0-2])-(\d\d)\b/g, (_, m, dd) => `2026-${String(+m - 6).padStart(2, "0")}-${dd}`);
    const walk = (o) => Array.isArray(o) ? o.map(walk) : o && typeof o === "object" ? Object.fromEntries(Object.entries(o).map(([k, v]) => [k, walk(v)])) : typeof o === "string" ? sh(o) : o;
    if (R) R.set(x => walk(x));
    if (window.wcStore) window.wcStore.set(l => walk(l));
    if (window.cmStore) window.cmStore.set(x => walk(x));
    localStorage.setItem("skyops_dates_v2", "1");
  }
  if (!localStorage.getItem("skyops_dates_v3")) {
    const T = window.SKY_TODAY;
    if (window.cmStore) window.cmStore.set(x => ({ ...x, quotes: x.quotes.map(q => q.date > T ? { ...q, date: T, valid: window.skyAdd(30) } : q) }));
    if (window.wcStore) window.wcStore.set(l => l.map(c => ({ ...c, ...(c.created > T ? { created: T } : {}), ...(c.submitted && c.submitted > T ? { submitted: T } : {}) })));
    localStorage.setItem("skyops_dates_v3", "1");
  }

  // 5. Site summary derived from inspections
  S.forEach(s => {
    const mi = I.filter(i => i.siteId === s.id);
    if (!mi.length) return;
    const d0 = (i) => i.startedAt || i.plannedFor || "";
    const flown = mi.filter(i => (i.progress?.flying || 0) > 0 && d0(i)).sort((a, b) => d0(b).localeCompare(d0(a)));
    const sched = mi.filter(i => (i.progress?.flying || 0) === 0 && i.plannedFor).sort((a, b) => a.plannedFor.localeCompare(b.plannedFor));
    if (flown[0]) s.lastInspection = d0(flown[0]);
    if (sched[0]) s.nextInspection = sched[0].plannedFor;
    const latestDone = flown.find(i => i.detections);
    if (latestDone && s.lastInspection !== "—" && (s.criticals == null || s.health === 100)) {
      s.criticals = latestDone.critical || 0;
      s.coverage = latestDone.coverage || s.coverage;
      if (s.health === 100 && latestDone.critical) s.health = Math.max(60, 100 - latestDone.critical * 2);
    }
  });
})();
