import { config } from "dotenv";
import path from "node:path";
config({ path: path.resolve(process.cwd(), ".env.local") });
config({ path: path.resolve(process.cwd(), ".env") });

type Milestone = {
  title: string;
  date: string;
  description: string;
  status: "done" | "active" | "upcoming";
};

const STUDY_EXTRAS: Record<
  string,
  {
    specialty: string;
    themes: string[];
    featured: boolean;
    protocolVersion: string;
    ethicsRef: string;
    timelineMilestones: Milestone[];
  }
> = {
  "og-rcr-outcomes-registry": {
    specialty: "Shoulder",
    themes: ["Rotator cuff", "Outcomes registry", "Multi-site"],
    featured: true,
    protocolVersion: "2.1",
    ethicsRef: "UK REC 24/WS/0041",
    timelineMilestones: [
      {
        title: "Protocol approved",
        date: "Mar 2024",
        description: "Multi-centre REC approval with 7 initial sites.",
        status: "done",
      },
      {
        title: "First patient enrolled",
        date: "Jun 2024",
        description:
          "University College London Hospitals enrolled the first participant.",
        status: "done",
      },
      {
        title: "Active recruitment",
        date: "Ongoing",
        description: "Currently open across 5 UK + 3 EU sites.",
        status: "active",
      },
      {
        title: "Target enrolment (1,500 patients)",
        date: "Q4 2026",
        description: "Planned completion of primary recruitment.",
        status: "upcoming",
      },
      {
        title: "Primary analysis",
        date: "Q2 2027",
        description: "Locked data and primary outcome publication.",
        status: "upcoming",
      },
    ],
  },
  "og-hip-fracture-frailty-cohort": {
    specialty: "Hip",
    themes: ["Hip fracture", "Frailty", "Geriatric orthopaedics"],
    featured: true,
    protocolVersion: "1.3",
    ethicsRef: "UK REC 25/SC/0102",
    timelineMilestones: [
      {
        title: "Protocol submitted",
        date: "Nov 2024",
        description: "Submitted to Scotland A REC for multi-site approval.",
        status: "done",
      },
      {
        title: "Active recruitment",
        date: "Feb 2025 – ongoing",
        description: "Four UK sites actively enrolling.",
        status: "active",
      },
      {
        title: "Interim analysis",
        date: "Q1 2026",
        description: "Frailty score calibration + sample size reassessment.",
        status: "upcoming",
      },
    ],
  },
  "og-acl-trial": {
    specialty: "Knee",
    themes: ["ACL reconstruction", "RCT", "Young athletes"],
    featured: false,
    protocolVersion: "0.9 draft",
    ethicsRef: "Pending REC submission",
    timelineMilestones: [
      {
        title: "Protocol drafting",
        date: "Jun 2025",
        description: "Draft circulated with the steering committee.",
        status: "active",
      },
      {
        title: "REC submission",
        date: "Q4 2025",
        description: "Target submission date to UK REC.",
        status: "upcoming",
      },
    ],
  },
};

const PUBLICATIONS: Array<{
  studySlug: string;
  title: string;
  authors: string[];
  journal: string;
  year: number;
  doi: string;
  type: "journal" | "preprint" | "poster";
}> = [
  {
    studySlug: "og-rcr-outcomes-registry",
    title:
      "Protocol for a multicentre outcomes registry of arthroscopic rotator cuff repair (OG-RCR)",
    authors: ["Imam M.A.", "Hassan A.", "et al."],
    journal: "BMJ Open",
    year: 2024,
    doi: "10.1136/bmjopen-2024-rcr",
    type: "journal",
  },
  {
    studySlug: "og-rcr-outcomes-registry",
    title:
      "Early recruitment findings from the OrthoGlobe rotator cuff registry — first 100 patients",
    authors: ["OrthoGlobe Research Collaborative"],
    journal: "EFORT Open Reviews",
    year: 2025,
    doi: "10.1530/EOR-25-0044",
    type: "journal",
  },
  {
    studySlug: "og-hip-fracture-frailty-cohort",
    title:
      "Designing a frailty-stratified outcomes cohort for hip fracture in older adults",
    authors: ["Gebaly A.", "Imam M.A.", "Hammad R.", "et al."],
    journal: "Age and Ageing (preprint)",
    year: 2025,
    doi: "10.1101/2025.03.hffc",
    type: "preprint",
  },
];

async function main() {
  if (!process.env.DATABASE_URL) throw new Error("DATABASE_URL not set");
  const postgres = (await import("postgres")).default;
  const { drizzle } = await import("drizzle-orm/postgres-js");
  const { eq, and } = await import("drizzle-orm");
  const schema = await import("../src/lib/db/schema");
  const sql = postgres(process.env.DATABASE_URL!, { max: 1 });
  const db = drizzle(sql, { schema });

  let touched = 0;
  for (const [slug, extras] of Object.entries(STUDY_EXTRAS)) {
    const [row] = await db
      .select({ id: schema.researchStudiesTable.id })
      .from(schema.researchStudiesTable)
      .where(eq(schema.researchStudiesTable.slug, slug))
      .limit(1);
    if (!row) {
      console.log(`skip: ${slug} (no such study)`);
      continue;
    }
    await db
      .update(schema.researchStudiesTable)
      .set({
        featured: extras.featured,
        specialty: extras.specialty,
        themes: extras.themes,
        timelineMilestones: extras.timelineMilestones,
        protocolVersion: extras.protocolVersion,
        ethicsRef: extras.ethicsRef,
      })
      .where(eq(schema.researchStudiesTable.id, row.id));
    touched += 1;
    console.log(`updated ${slug}`);
  }

  let pubInserted = 0;
  for (const p of PUBLICATIONS) {
    const [study] = await db
      .select({ id: schema.researchStudiesTable.id })
      .from(schema.researchStudiesTable)
      .where(eq(schema.researchStudiesTable.slug, p.studySlug))
      .limit(1);
    if (!study) continue;
    const existing = await db
      .select({ id: schema.researchPublications.id })
      .from(schema.researchPublications)
      .where(
        and(
          eq(schema.researchPublications.studyId, study.id),
          eq(schema.researchPublications.title, p.title),
        ),
      )
      .limit(1);
    if (existing.length > 0) continue;
    await db.insert(schema.researchPublications).values({
      studyId: study.id,
      title: p.title,
      authors: p.authors,
      journal: p.journal,
      year: p.year,
      doi: p.doi,
      type: p.type,
    });
    pubInserted += 1;
  }

  // One sample update per featured study so the public detail page shows
  // the new Updates block immediately.
  const UPDATES: Array<{ studySlug: string; title: string; body: string }> = [
    {
      studySlug: "og-rcr-outcomes-registry",
      title: "250th participant enrolled",
      body:
        "The registry crossed the 250-participant milestone this week, with strong recruitment at the Oxford and Manchester sites. Data cleaning is on schedule and the first interim analysis is planned for Q2 2026.",
    },
    {
      studySlug: "og-hip-fracture-frailty-cohort",
      title: "Frailty score calibration complete",
      body:
        "Clinical Frailty Scale coding calibrated across all four sites using paired review of 120 records. Kappa 0.84. The locked scoring guide is available in the Documents panel.",
    },
  ];

  for (const u of UPDATES) {
    const [study] = await db
      .select({ id: schema.researchStudiesTable.id })
      .from(schema.researchStudiesTable)
      .where(eq(schema.researchStudiesTable.slug, u.studySlug))
      .limit(1);
    if (!study) continue;
    const existing = await db
      .select({ id: schema.researchUpdates.id })
      .from(schema.researchUpdates)
      .where(
        and(
          eq(schema.researchUpdates.studyId, study.id),
          eq(schema.researchUpdates.title, u.title),
        ),
      )
      .limit(1);
    if (existing.length > 0) continue;
    await db.insert(schema.researchUpdates).values({
      studyId: study.id,
      title: u.title,
      body: u.body,
      postedByName: "OrthoGlobe Research Team",
      postedAt: new Date(),
    });
  }

  console.log(
    `\nSeed complete — studies updated: ${touched}, publications inserted: ${pubInserted}`,
  );
  await sql.end();
}

main()
  .then(() => process.exit(0))
  .catch((err) => {
    console.error(err);
    process.exit(1);
  });
