import { z } from "zod";

/**
 * student-bff 环境变量 schema.
 *
 * 仲裁依据:
 *   - coord-final-decisions §2 B2 (gRPC 首次实现即用, 6 个下游 gRPC URL)
 *   - coord-final-decisions §2 B6 (Redis 缓存 5-30s)
 *   - coord-final-decisions §1 G7 (Zod 验证)
 *   - president-final-rulings §2.4 (/readyz 探针按阶段扩展, env 控制启用)
 *   - port-allocation.md (3009 HTTP, 无 gRPC 对外)
 */
const envSchema = z.object({
  NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
  PORT: z.coerce.number().int().positive().default(3009),
  LOG_LEVEL: z
    .enum(["fatal", "error", "warn", "info", "debug", "trace"])
    .default("info"),

  // 下游 gRPC URL (按阶段启用, president §2.4)
  IAM_GRPC_URL: z.string().default("localhost:50052"),
  CORE_EDU_GRPC_URL: z.string().default("localhost:50053"),
  CONTENT_GRPC_URL: z.string().default("localhost:50054"),
  DATA_ANA_GRPC_URL: z.string().default("localhost:50055"),
  MSG_GRPC_URL: z.string().default("localhost:50056"),
  AI_GRPC_URL: z.string().default("localhost:50058"),

  // 下游 gRPC 调用参数
  DOWNSTREAM_TIMEOUT_MS: z.coerce.number().int().positive().default(5000),
  DOWNSTREAM_RETRY_COUNT: z.coerce.number().int().min(0).default(2),
  DOWNSTREAM_RETRY_BACKOFF_MS: z.coerce.number().int().positive().default(100),

  // Mock 模式 (上游未就绪时返回固定数据, workline §5)
  MOCK_UPSTREAM: z
    .preprocess((v) => v === "true" || v === true, z.boolean())
    .default(true),

  // DEV_MODE: 越权防御放行 (president §2.9 方案 D)
  DEV_MODE: z
    .preprocess((v) => v === "true" || v === true, z.boolean())
    .default(false),

  // Redis (B6 缓存 + P5 Kafka 幂等去重)
  REDIS_URL: z.string().default("redis://localhost:6379"),
  REDIS_KEY_PREFIX: z.string().default("student:"),

  // OTel (G6 全链路)
  OTEL_EXPORTER_OTLP_ENDPOINT: z.string().url().optional(),
  OTEL_SERVICE_NAME: z.string().default("student-bff"),

  // P5: Kafka + push-gateway
  KAFKA_BROKERS: z.string().default("localhost:9092"),
  KAFKA_CLIENT_ID: z.string().default("student-bff"),
  KAFKA_CONSUMER_GROUP: z.string().default("student-bff-event-subscriber"),
  PUSH_GATEWAY_URL: z.string().default("http://localhost:8081"),

  // GraphQL Playground (仅开发)
  GRAPHQL_PLAYGROUND: z
    .preprocess((v) => v === "true" || v === true, z.boolean())
    .default(true),
});

export type Env = z.infer<typeof envSchema>;

export function loadEnv(): Env {
  const result = envSchema.safeParse(process.env);
  if (!result.success) {
    throw new Error(
      "Invalid student-bff env: " + JSON.stringify(result.error.flatten()),
    );
  }
  return result.data;
}

export const env: Env = loadEnv();
