// Code generated by protoc-gen-ts-server. DO NOT EDIT.
// source: worldmonitor/forecast/v1/service.proto

export interface GetForecastsRequest {
  domain: string;
  region: string;
}

export interface GetForecastsResponse {
  forecasts: Forecast[];
  generatedAt: number;
}

export interface Forecast {
  id: string;
  domain: string;
  region: string;
  title: string;
  scenario: string;
  feedSummary: string;
  probability: number;
  confidence: number;
  timeHorizon: string;
  signals: ForecastSignal[];
  cascades: CascadeEffect[];
  trend: string;
  priorProbability: number;
  calibration?: CalibrationInfo;
  createdAt: number;
  updatedAt: number;
  perspectives?: Perspectives;
  projections?: Projections;
  caseFile?: ForecastCase;
  simulationAdjustment: number;
  simPathConfidence: number;
  demotedBySimulation: boolean;
}

export interface ForecastSignal {
  type: string;
  value: string;
  weight: number;
}

export interface CascadeEffect {
  domain: string;
  effect: string;
  probability: number;
}

export interface CalibrationInfo {
  marketTitle: string;
  marketPrice: number;
  drift: number;
  source: string;
}

export interface Perspectives {
  strategic: string;
  regional: string;
  contrarian: string;
}

export interface Projections {
  h24: number;
  d7: number;
  d30: number;
}

export interface ForecastCase {
  supportingEvidence: ForecastCaseEvidence[];
  counterEvidence: ForecastCaseEvidence[];
  triggers: string[];
  actorLenses: string[];
  baseCase: string;
  escalatoryCase: string;
  contrarianCase: string;
  changeSummary: string;
  changeItems: string[];
  actors: ForecastActor[];
  worldState?: ForecastWorldState;
  branches: ForecastBranch[];
}

export interface ForecastCaseEvidence {
  type: string;
  summary: string;
  weight: number;
}

export interface ForecastActor {
  id: string;
  name: string;
  category: string;
  role: string;
  objectives: string[];
  constraints: string[];
  likelyActions: string[];
  influenceScore: number;
}

export interface ForecastWorldState {
  summary: string;
  activePressures: string[];
  stabilizers: string[];
  keyUnknowns: string[];
}

export interface ForecastBranch {
  kind: string;
  title: string;
  summary: string;
  outcome: string;
  projectedProbability: number;
  rounds: ForecastBranchRound[];
}

export interface ForecastBranchRound {
  round: number;
  focus: string;
  developments: string[];
  actorMoves: string[];
  probabilityShift: number;
}

export interface GetSimulationPackageRequest {
  runId: string;
}

export interface GetSimulationPackageResponse {
  found: boolean;
  runId: string;
  pkgKey: string;
  schemaVersion: string;
  theaterCount: number;
  generatedAt: number;
  note: string;
  error: string;
}

export interface GetSimulationOutcomeRequest {
  runId: string;
}

export interface GetSimulationOutcomeResponse {
  found: boolean;
  runId: string;
  outcomeKey: string;
  schemaVersion: string;
  theaterCount: number;
  generatedAt: number;
  note: string;
  error: string;
  theaterSummariesJson: string;
}

export interface FieldViolation {
  field: string;
  description: string;
}

export class ValidationError extends Error {
  violations: FieldViolation[];

  constructor(violations: FieldViolation[]) {
    super("Validation failed");
    this.name = "ValidationError";
    this.violations = violations;
  }
}

export class ApiError extends Error {
  statusCode: number;
  body: string;

  constructor(statusCode: number, message: string, body: string) {
    super(message);
    this.name = "ApiError";
    this.statusCode = statusCode;
    this.body = body;
  }
}

export interface ServerContext {
  request: Request;
  pathParams: Record<string, string>;
  headers: Record<string, string>;
}

export interface ServerOptions {
  onError?: (error: unknown, req: Request) => Response | Promise<Response>;
  validateRequest?: (methodName: string, body: unknown) => FieldViolation[] | undefined;
}

export interface RouteDescriptor {
  method: string;
  path: string;
  handler: (req: Request) => Promise<Response>;
}

export interface ForecastServiceHandler {
  getForecasts(ctx: ServerContext, req: GetForecastsRequest): Promise<GetForecastsResponse>;
  getSimulationPackage(ctx: ServerContext, req: GetSimulationPackageRequest): Promise<GetSimulationPackageResponse>;
  getSimulationOutcome(ctx: ServerContext, req: GetSimulationOutcomeRequest): Promise<GetSimulationOutcomeResponse>;
}

export function createForecastServiceRoutes(
  handler: ForecastServiceHandler,
  options?: ServerOptions,
): RouteDescriptor[] {
  return [
    {
      method: "GET",
      path: "/api/forecast/v1/get-forecasts",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const url = new URL(req.url, "http://localhost");
          const params = url.searchParams;
          const body: GetForecastsRequest = {
            domain: params.get("domain") ?? "",
            region: params.get("region") ?? "",
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("getForecasts", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

          const ctx: ServerContext = {
            request: req,
            pathParams,
            headers: Object.fromEntries(req.headers.entries()),
          };

          const result = await handler.getForecasts(ctx, body);
          return new Response(JSON.stringify(result as GetForecastsResponse), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (err: unknown) {
          if (err instanceof ValidationError) {
            return new Response(JSON.stringify({ violations: err.violations }), {
              status: 400,
              headers: { "Content-Type": "application/json" },
            });
          }
          if (options?.onError) {
            return options.onError(err, req);
          }
          const message = err instanceof Error ? err.message : String(err);
          return new Response(JSON.stringify({ message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
    {
      method: "GET",
      path: "/api/forecast/v1/get-simulation-package",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const url = new URL(req.url, "http://localhost");
          const params = url.searchParams;
          const body: GetSimulationPackageRequest = {
            runId: params.get("runId") ?? "",
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("getSimulationPackage", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

          const ctx: ServerContext = {
            request: req,
            pathParams,
            headers: Object.fromEntries(req.headers.entries()),
          };

          const result = await handler.getSimulationPackage(ctx, body);
          return new Response(JSON.stringify(result as GetSimulationPackageResponse), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (err: unknown) {
          if (err instanceof ValidationError) {
            return new Response(JSON.stringify({ violations: err.violations }), {
              status: 400,
              headers: { "Content-Type": "application/json" },
            });
          }
          if (options?.onError) {
            return options.onError(err, req);
          }
          const message = err instanceof Error ? err.message : String(err);
          return new Response(JSON.stringify({ message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
    {
      method: "GET",
      path: "/api/forecast/v1/get-simulation-outcome",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const url = new URL(req.url, "http://localhost");
          const params = url.searchParams;
          const body: GetSimulationOutcomeRequest = {
            runId: params.get("runId") ?? "",
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("getSimulationOutcome", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

          const ctx: ServerContext = {
            request: req,
            pathParams,
            headers: Object.fromEntries(req.headers.entries()),
          };

          const result = await handler.getSimulationOutcome(ctx, body);
          return new Response(JSON.stringify(result as GetSimulationOutcomeResponse), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (err: unknown) {
          if (err instanceof ValidationError) {
            return new Response(JSON.stringify({ violations: err.violations }), {
              status: 400,
              headers: { "Content-Type": "application/json" },
            });
          }
          if (options?.onError) {
            return options.onError(err, req);
          }
          const message = err instanceof Error ? err.message : String(err);
          return new Response(JSON.stringify({ message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
  ];
}

