/**
 * "Add sample articles": four starter articles for Thought Leadership & Articles, written
 * from what the website says about Unionists Group, with the categories they use (the
 * design's tabs). Created as English drafts; nothing goes live until published.
 *
 * The API only accepts images from the media library, so the site's own pictures used
 * here are uploaded first (an earlier upload with the same title is reused).
 */
import { ApiError, apiPaged, errorMessage } from "./api";
import { articleCategoriesApi, articlesApi, sendArticle, type ArticleBlock, type ArticleText } from "./articles";
import type { Img } from "./cms";
import { MEDIA_ORIGIN, mediaUrl, uploadMedia, type Media } from "./media";

/** The design's category tabs, in its order. */
export const SAMPLE_CATEGORIES = [
  { slug: "ai-supply-chain", name: "AI & Supply Chain" },
  { slug: "sustainability-ethical-sourcing", name: "Sustainability & Ethical Sourcing" },
  { slug: "market-trends-global-trade", name: "Market Trends & Global Trade Insights" },
  { slug: "ai-powered-agriculture", name: "AI-Powered Agriculture" },
];

/** A picture from the website (public/assets/images/…) and its alt text. */
type SiteImage = { file: string; alt: string };

type SampleArticle = {
  slug: string;
  category: string;
  cover: SiteImage;
  text: Omit<ArticleText, "body">;
  /** Image blocks name a site picture instead of a URL; it's uploaded first. */
  body: (ArticleBlock | { type: "image"; site: SiteImage; caption?: string })[];
};

const AUTHOR = { name: "Unionists Editorial Team", role: "Thought Leadership" };
const p = (text: string): ArticleBlock => ({ type: "paragraph", text });
const h2 = (text: string): ArticleBlock => ({ type: "heading", level: 2, text });
const h3 = (text: string): ArticleBlock => ({ type: "heading", level: 3, text });
const bullets = (...items: string[]): ArticleBlock => ({ type: "list", style: "bullet", items });
const steps = (...items: string[]): ArticleBlock => ({ type: "list", style: "numbered", items });
const quote = (text: string): ArticleBlock => ({ type: "quote", text, source: "Unionists Group" });

export const SAMPLE_ARTICLES: SampleArticle[] = [
  {
    slug: "ai-and-automation-in-global-food-logistics",
    category: "ai-supply-chain",
    cover: { file: "thought-leadership/article-thumb.png", alt: "Automated fruit processing line with conveyor belts" },
    text: {
      title: "AI & Automation in Global Food Logistics",
      excerpt: "How artificial intelligence is changing the way food moves from farm to shelf: fewer delays, less waste and supply chains that see problems before they happen.",
      seo: { title: "AI & Automation in Global Food Logistics", description: "How AI and automation make global food supply chains faster, safer and less wasteful, from harvest to delivery." },
    },
    body: [
      p("Food is one of the hardest products to move around the world. It is perishable, seasonal and sensitive to temperature, and it crosses borders with strict quality and safety rules. A delay of a few days that would not matter for most goods can turn a shipment of fresh produce into waste."),
      p("For decades the industry managed this with experience, buffers and paperwork. Today, artificial intelligence and automation give logistics teams something new: the ability to see what is happening across the whole chain, and to act before small problems become expensive ones."),
      h2("From reacting to predicting"),
      p("Traditional logistics reacts. A container is late, a warehouse is full, a temperature alarm goes off, and someone starts making phone calls. AI-driven logistics predicts. By combining shipping schedules, weather data, port congestion, historical demand and live sensor readings, forecasting models can flag a likely delay days in advance and suggest another route, carrier or hub."),
      bullets(
        "Demand forecasting that matches harvests and production to what markets will actually buy",
        "Route optimisation that weighs cost, transit time and the shelf life of each product",
        "Cold-chain monitoring with sensors that report temperature and humidity in real time",
        "Automated sorting and grading lines that check quality consistently at high speed",
      ),
      { type: "image", site: { file: "media-insights/news-supply-chain.png", alt: "Worker sorting fresh vegetables on a processing line" }, caption: "Automated grading helps every crate meet the same quality standard." },
      h2("Less waste, more trust"),
      p("Every tonne of food that spoils on the way is lost twice: once as food, and again as the water, energy and labour that went into producing it. Better forecasts and faster decisions reduce that loss. They also build trust with partners, because buyers get consistent quality and reliable delivery dates, and suppliers get paid for what they ship instead of what arrives."),
      quote("The goal of AI in logistics is not to replace people. It is to give the people who run the supply chain a clearer view, earlier."),
      h2("What comes next"),
      p("The next step is connecting these systems end to end: traceability from the field to the final customer, shared data between producers, carriers and buyers, and automated warehouses that plan their own capacity. Unionists Group is investing in AI-powered logistics hubs so that our partners can trade with more speed, more certainty and less waste."),
    ],
  },
  {
    slug: "planting-a-forest-with-every-order",
    category: "sustainability-ethical-sourcing",
    cover: { file: "sustainability-esg/esg-forest-planting.jpg", alt: "Person planting a seedling in rich soil" },
    text: {
      title: "Planting a Forest With Every Order: Trade That Gives Back",
      excerpt: "Why Unionists Group links every order to reforestation, and how ethical sourcing and environmental restoration can be part of everyday business rather than an afterthought.",
      seo: { title: "Planting a Forest With Every Order", description: "How Unionists Group connects global trade to reforestation, carbon offsetting and ethical sourcing." },
    },
    body: [
      p("Global trade has a footprint. Fields are cleared, goods are shipped across oceans and packaging is produced at enormous scale. For a company that trades food and natural ingredients around the world, ignoring that footprint is not an option."),
      p("That is why Unionists Group made a simple commitment: for every order placed, we plant a forest. Reforestation is built into the way we do business, so that growth in trade also means growth in trees."),
      h2("Why forests"),
      bullets(
        "Trees capture carbon and help offset the emissions of transport and processing",
        "Forests protect soil and water, which the farmers we work with depend on",
        "Restored land supports biodiversity, from pollinators to wildlife corridors",
        "Planting projects create local jobs in the communities where they take place",
      ),
      h2("Ethical sourcing starts at the farm"),
      p("Planting trees only works alongside responsible sourcing. We work directly with agricultural communities to promote fair trade and sustainable farming methods, and we favour regenerative practices that keep soil healthy for the next harvest.\n\nWe also look at what happens after the harvest: reducing waste in production, packaging and distribution, and designing supply chains that use less energy per tonne delivered."),
      quote("Sustainability is not a separate project. It is a way of making every business decision."),
      h2("How the programme works"),
      steps(
        "An order is confirmed with one of our trading partners.",
        "A planting commitment is registered with a certified reforestation partner.",
        "Trees are planted and monitored in regions that need restoration.",
        "Progress is reported to our partners as part of our impact reporting.",
      ),
      { type: "image", site: { file: "sustainability-esg/esg-hero.jpg", alt: "Green agricultural landscape with wind turbines on the horizon" }, caption: "Healthy land and renewable energy go hand in hand." },
      p("Every partner who trades with us is part of this effort. Together, we can show that a global food business can be profitable, fair and good for the planet at the same time."),
    ],
  },
  {
    slug: "five-trends-reshaping-global-food-trade",
    category: "market-trends-global-trade",
    cover: { file: "global-presence/global-powerhouse-map.png", alt: "Stylized world map with glowing golden connection points across continents" },
    text: {
      title: "Five Trends Reshaping Global Food Trade",
      excerpt: "From regional trade hubs to traceability and natural ingredients, these are the shifts we see changing how food and ingredients are bought, sold and moved around the world.",
      seo: { title: "Five Trends Reshaping Global Food Trade", description: "Regional hubs, traceability, natural ingredients, digital trading and resilience: five shifts changing global food trade." },
    },
    body: [
      p("The global food trade is going through one of its biggest changes in decades. Supply shocks, climate pressure, new technology and changing consumer expectations are all pushing in the same direction: towards supply chains that are more resilient, more transparent and more connected."),
      p("Working with partners across continents, we see five trends shaping the years ahead."),
      h3("1. Regional hubs instead of single routes"),
      p("Companies are moving away from depending on one supplier or one shipping route. Networks of regional processing and logistics hubs make it possible to switch sources quickly and keep goods moving when one region is disrupted."),
      h3("2. Traceability becomes a requirement"),
      p("Buyers and regulators increasingly want to know where food comes from and how it was produced. Digital traceability, from farm to final customer, is becoming a condition for doing business rather than a bonus."),
      h3("3. Natural ingredients keep growing"),
      p("Demand for natural ingredients, organic products and clean-label foods continues to rise. Suppliers who can guarantee quality and certification at scale will have a clear advantage."),
      h3("4. Trading goes digital"),
      p("Quotes, contracts, quality documents and shipment tracking are moving onto digital platforms. This shortens deal cycles and reduces errors, especially for trade across borders and languages."),
      h3("5. Resilience is the new efficiency"),
      p("For years, the leanest supply chain was the best one. Recent disruptions have shown the cost of having no buffer. The new goal is a balance: efficient enough to compete, resilient enough to keep delivering when conditions change."),
      quote("The winners in food trade will be the companies that can see their whole supply chain and adapt it quickly."),
      h2("What this means for partners"),
      bullets(
        "Diversify sourcing across regions and suppliers",
        "Invest in data and traceability early, before it is mandatory",
        "Choose partners with their own logistics and processing capacity",
      ),
      p("Unionists Group is building its global presence around these trends, with trade hubs, AI-powered logistics and certified sourcing that help our partners stay ahead."),
    ],
  },
  {
    slug: "ai-powered-agriculture-from-field-to-forecast",
    category: "ai-powered-agriculture",
    cover: { file: "media-insights/news-ai-agriculture.png", alt: "Robotic arm harvesting tomatoes in a greenhouse" },
    text: {
      title: "From Field Sensors to Forecasts: AI-Powered Agriculture in Practice",
      excerpt: "Precision farming, smart greenhouses and robotics are changing how food is grown. A practical look at where AI helps farmers today and what it takes to get started.",
      seo: { title: "AI-Powered Agriculture in Practice", description: "Precision farming, smart greenhouses and agricultural robotics: where AI helps farmers today and how to start." },
    },
    body: [
      p("Agriculture has always depended on reading the land, the weather and the crop. What is changing is how much information farmers can now collect, and how quickly they can turn it into decisions."),
      h2("Where AI helps today"),
      bullets(
        "Soil and moisture sensors that show exactly where and when to irrigate",
        "Drone and satellite images that spot disease or pests before they spread",
        "Yield forecasts that help growers and buyers plan harvests and sales",
        "Climate control in greenhouses that adjusts light, heat and humidity automatically",
        "Robotic picking and handling that eases the pressure of seasonal labour shortages",
      ),
      { type: "image", site: { file: "ai-innovation-lab/lab-robotics-greenhouse.png", alt: "Robotic arm working in a modern greenhouse" }, caption: "Robotics in a controlled greenhouse environment." },
      h2("Precision instead of averages"),
      p("Traditional farming treats a whole field the same way: the same water, the same fertiliser, the same timing. Precision agriculture treats each part of the field according to what it needs. The result is less water and fewer inputs for the same or better harvest, which is good for both the farmer's margin and the environment."),
      quote("The best technology on a farm is the one that saves the grower time and gives the crop exactly what it needs."),
      h2("Getting started"),
      steps(
        "Start with one clear problem, such as water use or disease detection.",
        "Collect reliable data for a full season before automating decisions.",
        "Work with partners who understand both the technology and the crop.",
        "Scale what works, field by field.",
      ),
      p("Through our AI & Innovation Lab, Unionists Group is exploring how these tools can support the growers in our network, so that better farming leads to better supply for markets around the world."),
    ],
  },
];

export type SampleResult = { created: string[]; skipped: string[]; categories: string[]; failed: string[] };

/** A media-library copy of a website picture: an earlier upload with the same title, or a new upload. */
async function libraryImage(img: SiteImage, cache: Map<string, string>): Promise<Img> {
  const title = `Article – ${img.file.split("/").pop()!.replace(/\.[^.]+$/, "")}`;
  let url = cache.get(title);
  if (!url) {
    const found = await apiPaged<Media>("/admin/media", { search: title, kind: "image", limit: 5, page: 1 });
    const hit = found.data.find((m) => m.title === title);
    if (hit) url = mediaUrl(hit);
    else {
      const res = await fetch(`/assets/images/${img.file}`);
      if (!res.ok) throw new Error(`Couldn't load the picture ${img.file}`);
      const blob = await res.blob();
      const m = await uploadMedia(new File([blob], img.file.split("/").pop()!, { type: blob.type || "image/png" }), title);
      url = mediaUrl(m);
    }
    cache.set(title, url);
  }
  return { url, alt: img.alt };
}

/** Creates the missing categories, then each sample article not created yet (`existing` = slugs in the CMS). */
export async function addSampleArticles(existing: Set<string>, onProgress: (msg: string) => void): Promise<SampleResult> {
  const result: SampleResult = { created: [], skipped: [], categories: [], failed: [] };
  onProgress("Setting up the categories…");
  const cats = await articleCategoriesApi.list();
  const ids: Record<string, string> = {};
  for (const c of SAMPLE_CATEGORIES) {
    let cat = cats.find((x) => x.slug === c.slug);
    if (!cat) {
      cat = await articleCategoriesApi.create({ slug: c.slug, translations: { en: { name: c.name } } });
      result.categories.push(c.name);
    }
    ids[c.slug] = cat.id;
  }

  const images = new Map<string, string>();
  for (const [i, a] of SAMPLE_ARTICLES.entries()) {
    if (existing.has(a.slug)) {
      result.skipped.push(a.text.title);
      continue;
    }
    onProgress(`Creating "${a.text.title}" (${i + 1} of ${SAMPLE_ARTICLES.length})…`);
    try {
      const body: ArticleBlock[] = [];
      for (const b of a.body) {
        if ("site" in b) {
          const img = await libraryImage(b.site, images);
          body.push({ type: "image", url: img.url, alt: img.alt, ...(b.caption ? { caption: b.caption } : {}) });
        } else body.push(b);
      }
      await sendArticle(
        articlesApi.create,
        { slug: a.slug, categoryId: ids[a.category], coverImage: await libraryImage(a.cover, images), author: AUTHOR, translations: { en: { ...a.text, body } } },
        MEDIA_ORIGIN,
      );
      result.created.push(a.text.title);
    } catch (e) {
      if (e instanceof ApiError && e.status === 409) result.skipped.push(a.text.title);
      else result.failed.push(`${a.text.title}: ${errorMessage(e)}`);
    }
  }
  return result;
}
