import { z } from 'zod';
import { checkFlag } from './feature-flags';

// Environment variables for SpamShield
const envSchema = z.object({
  HIYA_API_KEY: z.string(),
  HIYA_API_URL: z.string().default('https://api.hiya.com/v1'),
  TRUECALLER_API_KEY: z.string().optional(),
  BERT_MODEL_PATH: z.string().default('./models/spam-classifier'),
  SPAM_THRESHOLD_AUTO_BLOCK: z.string().transform(Number).default(0.85),
  SPAM_THRESHOLD_FLAG: z.string().transform(Number).default(0.6),
  CALL_ANALYSIS_TIMEOUT_MS: z.string().transform(Number).default(200),
});

export const spamShieldEnv = envSchema.parse({
  HIYA_API_KEY: process.env.HIYA_API_KEY,
  HIYA_API_URL: process.env.HIYA_API_URL,
  TRUECALLER_API_KEY: process.env.TRUECALLER_API_KEY,
  BERT_MODEL_PATH: process.env.BERT_MODEL_PATH,
  SPAM_THRESHOLD_AUTO_BLOCK: process.env.SPAM_THRESHOLD_AUTO_BLOCK,
  SPAM_THRESHOLD_FLAG: process.env.SPAM_THRESHOLD_FLAG,
  CALL_ANALYSIS_TIMEOUT_MS: process.env.CALL_ANALYSIS_TIMEOUT_MS,
});

// Spam detection layers
export enum SpamLayer {
  NUMBER_REPUTATION = 'number_reputation',
  CONTENT_CLASSIFICATION = 'content_classification',
  BEHAVIORAL_ANALYSIS = 'behavioral_analysis',
  COMMUNITY_INTELLIGENCE = 'community_intelligence',
}

// Spam decision types
export enum SpamDecision {
  ALLOW = 'allow',
  FLAG = 'flag',
  BLOCK = 'block',
  CHALLENGE = 'challenge',
}

// Confidence levels
export enum ConfidenceLevel {
  LOW = 'low',
  MEDIUM = 'medium',
  HIGH = 'high',
  VERY_HIGH = 'very_high',
}

// Feature flags for spam detection
// Use the centralized feature flag system from feature-flags.ts
// These are aliases for quick access
export const spamFeatureFlags = {
  enableNumberReputation: checkFlag('spamshield.enable.number.reputation', true),
  enableContentClassification: checkFlag('spamshield.enable.content.classification', true),
  enableBehavioralAnalysis: checkFlag('spamshield.enable.behavioral.analysis', true),
  enableCommunityIntelligence: checkFlag('spamshield.enable.community.intelligence', true),
  enableRealTimeBlocking: checkFlag('spamshield.enable.real.time.blocking', true),
  enableMultipleSources: checkFlag('spamshield.enable.multiple.sources', false),
  enableMLClassifier: checkFlag('spamshield.enable.ml.classifier', false),
};

// Rate limits for spam analysis
export const spamRateLimits = {
  basic: {
    analysesPerMinute: 10,
    analysesPerDay: 100,
  },
  plus: {
    analysesPerMinute: 50,
    analysesPerDay: 1000,
  },
  premium: {
    analysesPerMinute: 200,
    analysesPerDay: 10000,
  },
};

// Default confidence scores for spam detection layers
export const defaultScores = {
  // Number reputation service defaults
  defaultReputationConfidence: 0.0,
  defaultReputationLowConfidence: 0.1,
  
  // SMS classifier defaults
  defaultBaseConfidence: 0.5,
  defaultMaxConfidence: 1.0,
  
  // Feature weights for SMS classification
  featureWeights: {
    urlPresent: 0.1,
    highEmojiDensity: 0.15,
    urgencyKeyword: 0.2,
    excessiveCaps: 0.15,
  },
  
  // Call analysis defaults
  defaultSpamScore: 0.0,
  highReputationThreshold: 0.7,
  reputationWeightInCombinedScore: 0.4,
  shortDurationScore: 0.2,
  voipScore: 0.15,
  unusualHoursScore: 0.1,
  
  // Source combination weights
  hiyaWeightInCombinedScore: 0.7,
  truecallerWeightInCombinedScore: 0.3,
};

// Metadata size limits for SpamFeedback
export const metadataLimits = {
  // Maximum size for metadata JSON in bytes
  maxMetadataSizeBytes: 4096,
  
  // Maximum number of keys in metadata object
  maxMetadataKeys: 20,
  
  // Maximum size for individual metadata value in bytes
  maxMetadataValueSizeBytes: 512,
};

// Standard error codes for spamshield API
export enum SpamErrorCode {
  // Client errors (4xx)
  INVALID_REQUEST = 'INVALID_REQUEST',
  MISSING_REQUIRED_FIELD = 'MISSING_REQUIRED_FIELD',
  UNAUTHORIZED = 'UNAUTHORIZED',
  NOT_FOUND = 'NOT_FOUND',
  VALIDATION_ERROR = 'VALIDATION_ERROR',
  
  // Server errors (5xx)
  CLASSIFICATION_FAILED = 'CLASSIFICATION_FAILED',
  REPUTATION_CHECK_FAILED = 'REPUTATION_CHECK_FAILED',
  ANALYSIS_FAILED = 'ANALYSIS_FAILED',
  FEEDBACK_RECORD_FAILED = 'FEEDBACK_RECORD_FAILED',
  DATABASE_ERROR = 'DATABASE_ERROR',
  RATE_LIMIT_EXCEEDED = 'RATE_LIMIT_EXCEEDED',
  SERVICE_UNAVAILABLE = 'SERVICE_UNAVAILABLE',
}

// Standard error response type
export interface SpamErrorResponse {
  error: {
    code: SpamErrorCode;
    message: string;
    field?: string;
    timestamp: string;
    requestId?: string;
  };
}

// HTTP status code constants
export const HttpStatus = {
  OK: 200,
  CREATED: 201,
  BAD_REQUEST: 400,
  UNAUTHORIZED: 401,
  FORBIDDEN: 403,
  NOT_FOUND: 404,
  UNPROCESSABLE_ENTITY: 422,
  TOO_MANY_REQUESTS: 429,
  INTERNAL_SERVER_ERROR: 500,
  SERVICE_UNAVAILABLE: 503,
};
