import { api, CONSTANTS } from "../../../data/fakeBackend";
import type { GalaxyConnection, GalaxySystem, SystemPlanet, SystemPointOfInterest } from "./types";

type CelestialBody = {
  name: string;
  type: string;
  orbit?: number;
  innerOrbit?: number;
  outerOrbit?: number;
  moons?: unknown[];
};

const formatType = (value: string) => value.replace(/_/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());

function getSystemPlanets(systemId: string): SystemPlanet[] {
  const detail = CONSTANTS.CELESTIAL_BODIES[systemId as keyof typeof CONSTANTS.CELESTIAL_BODIES];
  if (!detail) return [];

  return (detail.bodies as CelestialBody[])
    .filter((body) => body.type !== "belt")
    .map((body, index) => ({
      id: `${systemId}-planet-${index}`,
      name: body.name,
      type: formatType(body.type),
      orbit: body.orbit ?? 0,
      moons: body.moons?.length ?? 0,
    }));
}

function getSystemPointsOfInterest(system: { id: string; name: string; security: number; stations: string[] }): SystemPointOfInterest[] {
  const detail = CONSTANTS.CELESTIAL_BODIES[system.id as keyof typeof CONSTANTS.CELESTIAL_BODIES];
  const bodies = (detail?.bodies ?? []) as CelestialBody[];
  const stationPois = system.stations.map((station, index) => ({
    id: `${system.id}-station-${index}`,
    name: station,
    type: "station" as const,
    description: "Docking, repair, market access, and mission services.",
  }));
  const beltPois = bodies
    .filter((body) => body.type === "belt")
    .map((body, index) => ({
      id: `${system.id}-belt-${index}`,
      name: body.name,
      type: "asteroid_belt" as const,
      description: `Mining field spanning orbit ${body.innerOrbit ?? "?"}-${body.outerOrbit ?? "?"}.`,
    }));
  const routePois: SystemPointOfInterest[] = [
    {
      id: `${system.id}-stargate`,
      name: `${system.name} Stargate Network`,
      type: "stargate",
      description: "Linked gates to neighboring systems on the regional route graph.",
    },
  ];
  const anomalyPois: SystemPointOfInterest[] = system.security < 0.4
    ? [{
        id: `${system.id}-anomaly`,
        name: system.security < 0.2 ? "Unstable Deadspace Rift" : "Hidden Combat Site",
        type: "anomaly",
        description: "Scan signature with elevated risk and better rewards.",
      }]
    : [];

  return [...stationPois, ...beltPois, ...routePois, ...anomalyPois];
}

export async function loadGalaxyData(): Promise<{ systems: GalaxySystem[]; connections: GalaxyConnection[] }> {
  const [systems, connections] = await Promise.all([api.getSystems(), api.getConnections()]);
  return {
    systems: systems.map((system) => {
      const planets = getSystemPlanets(system.id);
      return {
        id: system.id,
        name: system.name,
        security: system.security,
        x: system.x,
        y: system.y,
        z: 0,
        mapProjection: "backend2d",
        faction: system.type,
        type: system.type,
        planetCount: planets.length || system.planets,
        planets,
        stations: [...system.stations],
        pointsOfInterest: getSystemPointsOfInterest(system),
        color: system.color,
      };
    }),
    connections: connections.map(([a, b]) => [a, b]),
  };
}
