/**
 * Interview & Media Prep Model
 * AI-powered interview coaching, media preparation, and communication training
 */

import mongoose, { Document, Schema } from 'mongoose';

// ============================================
// TYPES
// ============================================

export type PrepType =
  | 'podcast'
  | 'rapid-fire'
  | 'interview'
  | 'panel-discussion'
  | 'founder-interview'
  | 'employee-interview'
  | 'media-interview'
  | 'tv-interview'
  | 'press-conference'
  | 'journalist'
  | 'investor-interview'
  | 'startup-interview'
  | 'crisis-management'
  | 'product-launch'
  | 'custom';

export type SpeakerType =
  | 'founder'
  | 'employee'
  | 'ceo'
  | 'manager'
  | 'entrepreneur'
  | 'student'
  | 'other';

export type DifficultyLevel = 'beginner' | 'intermediate' | 'advanced' | 'expert';

export type AudienceType =
  | 'customers'
  | 'investors'
  | 'journalists'
  | 'government'
  | 'students'
  | 'business-owners'
  | 'developers'
  | 'general-public';

export type Language = 'english' | 'hindi' | 'marathi';

export type InterviewStatus = 'draft' | 'generating' | 'completed' | 'archived' | 'failed';

// ============================================
// INTERVIEW QUESTION
// ============================================

export interface IInterviewQuestion {
  id: string;
  question: string;
  category: string;
  difficulty: DifficultyLevel;
  suggestedAnswer?: string;
  expertAnswer?: string;
  shortAnswer?: string;
  longAnswer?: string;
  highConfidenceAnswer?: string;
  mediaFriendlyAnswer?: string;
  followUpQuestions?: string[];
  coachingTips?: string[];
  riskLevel?: 'low' | 'medium' | 'high';
  responseStrategy?: string;
  confidenceScore?: number;
  improvementSuggestions?: string[];
  order: number;
}

// ============================================
// COACHING TIP
// ============================================

export interface ICoachingTip {
  id: string;
  category: string;
  title: string;
  description: string;
  tips: string[];
  commonMistakes?: string[];
  confidenceTips?: string[];
  bodyLanguageTips?: string[];
  voiceModulationTips?: string[];
  cameraPresenceTips?: string[];
}

// ============================================
// INTERVIEW SESSION
// ============================================

export interface IInterviewSession {
  id: string;
  name: string;
  type: PrepType;
  status: InterviewStatus;
  speakerType: SpeakerType;
  difficulty: DifficultyLevel;
  language: Language;
  audienceType?: AudienceType;

  // Speaker Information (auto-filled or manual)
  speakerName: string;
  speakerPosition?: string;
  speakerCompany?: string;
  speakerIndustry?: string;
  speakerDepartment?: string;
  speakerBio?: string;

  // Context
  contextTopic?: string;
  contextIndustry?: string;
  contextAudience?: string;
  contextInterviewType?: string;

  // Generated Content
  questions: IInterviewQuestion[];
  coachingTips: ICoachingTip[];

  // Output Options
  questionCount: number;
  includeExpertAnswers: boolean;
  includeFollowUps: boolean;
  includeCoachingTips: boolean;

  // AI Generation Metadata
  aiGenerated: boolean;
  aiModel?: string;
  aiProvider?: string;
  aiTokensUsed?: number;
  aiGeneratedAt?: string;
  aiJobId?: string;
  /** Populated when status is 'failed'; explains why generation did not finish. */
  generationError?: string;

  // Linked Data
  linkedFounderId?: string;
  linkedEmployeeId?: string;
  linkedProductId?: string;
  linkedBrandId?: string;
  linkedIcpIds?: string[];
  linkedPersonaIds?: string[];

  // Data Sources Configuration
  dataSources?: {
    businessProfile?: boolean;
    brand?: boolean;
    brandStrategy?: boolean;
    icp?: boolean;
    persona?: boolean;
    founders?: boolean;
    employees?: boolean;
    products?: boolean;
    competitors?: boolean;
  };

  // Version & History
  version: number;
  parentSessionId?: string;

  // Metadata
  notes?: string;
  tags?: string[];

  createdAt: string;
  updatedAt: string;
}

// ============================================
// INTERVIEW PREP DOCUMENT
// ============================================

export interface IInterviewMediaPrep extends Document {
  companyId: string;
  userId: string;
  sessions: IInterviewSession[];
  totalSessions: number;
  createdAt: Date;
  updatedAt: Date;
}

// ============================================
// SCHEMA
// ============================================

const InterviewQuestionSchema = new Schema<IInterviewQuestion>({
  id: { type: String, required: true },
  question: { type: String, required: true },
  category: { type: String, required: true },
  difficulty: {
    type: String,
    enum: ['beginner', 'intermediate', 'advanced', 'expert'],
    default: 'intermediate'
  },
  suggestedAnswer: { type: String },
  expertAnswer: { type: String },
  shortAnswer: { type: String },
  longAnswer: { type: String },
  highConfidenceAnswer: { type: String },
  mediaFriendlyAnswer: { type: String },
  followUpQuestions: [{ type: String }],
  coachingTips: [{ type: String }],
  riskLevel: { type: String, enum: ['low', 'medium', 'high'] },
  responseStrategy: { type: String },
  confidenceScore: { type: Number, min: 0, max: 100 },
  improvementSuggestions: [{ type: String }],
  order: { type: Number, default: 0 }
}, { _id: false });

const CoachingTipSchema = new Schema<ICoachingTip>({
  id: { type: String, required: true },
  category: { type: String, required: true },
  title: { type: String, required: true },
  description: { type: String },
  tips: [{ type: String }],
  commonMistakes: [{ type: String }],
  confidenceTips: [{ type: String }],
  bodyLanguageTips: [{ type: String }],
  voiceModulationTips: [{ type: String }],
  cameraPresenceTips: [{ type: String }]
}, { _id: false });

const InterviewSessionSchema = new Schema<IInterviewSession>({
  id: { type: String, required: true },
  name: { type: String, required: true },
  type: {
    type: String,
    enum: [
      'podcast',
      'rapid-fire',
      'interview',
      'panel-discussion',
      'founder-interview',
      'employee-interview',
      'media-interview',
      'tv-interview',
      'press-conference',
      'journalist',
      'investor-interview',
      'startup-interview',
      'crisis-management',
      'product-launch',
      'custom'
    ],
    required: true
  },
  status: {
    type: String,
    enum: ['draft', 'generating', 'completed', 'archived', 'failed'],
    default: 'draft'
  },
  speakerType: {
    type: String,
    enum: ['founder', 'employee', 'ceo', 'manager', 'entrepreneur', 'student', 'other'],
    required: true
  },
  difficulty: {
    type: String,
    enum: ['beginner', 'intermediate', 'advanced', 'expert'],
    default: 'intermediate'
  },
  language: {
    type: String,
    enum: ['english', 'hindi', 'marathi'],
    default: 'english'
  },
  audienceType: {
    type: String,
    enum: ['customers', 'investors', 'journalists', 'government', 'students', 'business-owners', 'developers', 'general-public']
  },

  // Speaker Information
  speakerName: { type: String, required: true },
  speakerPosition: { type: String },
  speakerCompany: { type: String },
  speakerIndustry: { type: String },
  speakerDepartment: { type: String },
  speakerBio: { type: String },

  // Context
  contextTopic: { type: String },
  contextIndustry: { type: String },
  contextAudience: { type: String },
  contextInterviewType: { type: String },

  // Generated Content
  questions: [InterviewQuestionSchema],
  coachingTips: [CoachingTipSchema],

  // Output Options
  questionCount: { type: Number, default: 10 },
  includeExpertAnswers: { type: Boolean, default: true },
  includeFollowUps: { type: Boolean, default: true },
  includeCoachingTips: { type: Boolean, default: true },

  // AI Generation Metadata
  aiGenerated: { type: Boolean, default: false },
  aiModel: { type: String },
  aiProvider: { type: String },
  aiTokensUsed: { type: Number },
  aiGeneratedAt: { type: String },
  aiJobId: { type: String },
  generationError: { type: String },

  // Linked Data
  linkedFounderId: { type: String },
  linkedEmployeeId: { type: String },
  linkedProductId: { type: String },
  linkedBrandId: { type: String },
  linkedIcpIds: [{ type: String }],
  linkedPersonaIds: [{ type: String }],

  // Data Sources Configuration
  dataSources: {
    businessProfile: { type: Boolean, default: true },
    brand: { type: Boolean, default: true },
    brandStrategy: { type: Boolean, default: true },
    icp: { type: Boolean, default: true },
    persona: { type: Boolean, default: true },
    founders: { type: Boolean, default: true },
    employees: { type: Boolean, default: false },
    products: { type: Boolean, default: false },
    competitors: { type: Boolean, default: false }
  },

  // Version & History
  version: { type: Number, default: 1 },
  parentSessionId: { type: String },

  // Metadata
  notes: { type: String },
  tags: [{ type: String }],

  // Managed explicitly as ISO strings by the routes rather than by Mongoose
  // (hence timestamps: false below). These must stay declared: without them
  // strict mode silently drops the values the routes write, which left every
  // session with no created date and nothing to age a stuck row against.
  createdAt: { type: String },
  updatedAt: { type: String }
}, { _id: false, timestamps: false });

const InterviewMediaPrepSchema = new Schema<IInterviewMediaPrep>({
  companyId: {
    type: String,
    required: [true, 'Company ID is required'],
    index: true
  },
  userId: {
    type: String,
    required: [true, 'User ID is required'],
    index: true
  },
  sessions: [InterviewSessionSchema],
  totalSessions: {
    type: Number,
    default: 0
  }
}, {
  timestamps: true
});

// Indexes
InterviewMediaPrepSchema.index({ companyId: 1, userId: 1 });
InterviewMediaPrepSchema.index({ companyId: 1, 'sessions.type': 1 });
InterviewMediaPrepSchema.index({ companyId: 1, 'sessions.status': 1 });
InterviewMediaPrepSchema.index({ companyId: 1, 'sessions.createdAt': -1 });

// Model export
export const InterviewMediaPrep = mongoose.models.InterviewMediaPrep ||
  mongoose.model<IInterviewMediaPrep>('InterviewMediaPrep', InterviewMediaPrepSchema);

// Also export a separate model for individual sessions if needed
export const InterviewSession = mongoose.models.InterviewSession ||
  mongoose.model('InterviewSession', InterviewSessionSchema);