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

export interface SummarizeArticleRequest {
  provider: string;
  headlines: string[];
  mode: string;
  geoContext: string;
  variant: string;
  lang: string;
  systemAppend: string;
  bodies: string[];
}

export interface SummarizeArticleResponse {
  summary: string;
  model: string;
  provider: string;
  tokens: number;
  fallback: boolean;
  error: string;
  errorType: string;
  status: SummarizeStatus;
  statusDetail: string;
}

export interface GetSummarizeArticleCacheRequest {
  cacheKey: string;
}

export interface ListFeedDigestRequest {
  variant: string;
  lang: string;
}

export interface ListFeedDigestResponse {
  categories: Record<string, CategoryBucket>;
  feedStatuses: Record<string, string>;
  generatedAt: string;
}

export interface CategoryBucket {
  items: NewsItem[];
}

export interface NewsItem {
  source: string;
  title: string;
  link: string;
  publishedAt: number;
  isAlert: boolean;
  threat?: ThreatClassification;
  location?: GeoCoordinates;
  locationName: string;
  importanceScore: number;
  corroborationCount: number;
  storyMeta?: StoryMeta;
  snippet: string;
}

export interface ThreatClassification {
  level: ThreatLevel;
  category: string;
  confidence: number;
  source: string;
}

export interface GeoCoordinates {
  latitude: number;
  longitude: number;
}

export interface StoryMeta {
  firstSeen: number;
  mentionCount: number;
  sourceCount: number;
  phase: StoryPhase;
}

export type StoryPhase = "STORY_PHASE_UNSPECIFIED" | "STORY_PHASE_BREAKING" | "STORY_PHASE_DEVELOPING" | "STORY_PHASE_SUSTAINED" | "STORY_PHASE_FADING";

export type SummarizeStatus = "SUMMARIZE_STATUS_UNSPECIFIED" | "SUMMARIZE_STATUS_SUCCESS" | "SUMMARIZE_STATUS_CACHED" | "SUMMARIZE_STATUS_SKIPPED" | "SUMMARIZE_STATUS_ERROR";

export type ThreatLevel = "THREAT_LEVEL_UNSPECIFIED" | "THREAT_LEVEL_LOW" | "THREAT_LEVEL_MEDIUM" | "THREAT_LEVEL_HIGH" | "THREAT_LEVEL_CRITICAL";

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 NewsServiceHandler {
  summarizeArticle(ctx: ServerContext, req: SummarizeArticleRequest): Promise<SummarizeArticleResponse>;
  getSummarizeArticleCache(ctx: ServerContext, req: GetSummarizeArticleCacheRequest): Promise<SummarizeArticleResponse>;
  listFeedDigest(ctx: ServerContext, req: ListFeedDigestRequest): Promise<ListFeedDigestResponse>;
}

export function createNewsServiceRoutes(
  handler: NewsServiceHandler,
  options?: ServerOptions,
): RouteDescriptor[] {
  return [
    {
      method: "POST",
      path: "/api/news/v1/summarize-article",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const body = await req.json() as SummarizeArticleRequest;
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("summarizeArticle", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

          const result = await handler.summarizeArticle(ctx, body);
          return new Response(JSON.stringify(result as SummarizeArticleResponse), {
            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/news/v1/summarize-article-cache",
      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: GetSummarizeArticleCacheRequest = {
            cacheKey: params.get("cache_key") ?? "",
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("getSummarizeArticleCache", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

          const result = await handler.getSummarizeArticleCache(ctx, body);
          return new Response(JSON.stringify(result as SummarizeArticleResponse), {
            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/news/v1/list-feed-digest",
      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: ListFeedDigestRequest = {
            variant: params.get("variant") ?? "",
            lang: params.get("lang") ?? "",
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("listFeedDigest", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

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

          const result = await handler.listFeedDigest(ctx, body);
          return new Response(JSON.stringify(result as ListFeedDigestResponse), {
            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" },
          });
        }
      },
    },
  ];
}

