/**
 * Risk Assessment Service
 * Client for connecting to the Risk Assessment API
 */

const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:3080';

// ============================================================================
// Types
// ============================================================================

export type RiskProfile = 'conservative' | 'moderate' | 'aggressive';

export type TradingAgent = 'atlas' | 'orion' | 'nova';

export interface RiskQuestionOption {
  value: string;
  label: string;
  weight: number;
}

export interface RiskQuestion {
  id: string;
  text: string;
  category: 'experience' | 'goals' | 'timeframe' | 'volatility' | 'loss_reaction';
  options: RiskQuestionOption[];
}

export interface RiskQuestionnaireResponse {
  questionId: string;
  answer: string;
}

export interface RiskAssessment {
  id: string;
  userId: string;
  responses: Array<{
    questionId: string;
    answer: string;
    score: number;
  }>;
  totalScore: number;
  riskProfile: RiskProfile;
  recommendedAgent: TradingAgent | null;
  completedAt: string;
  expiresAt: string;
  isExpired: boolean;
  ipAddress: string | null;
  userAgent: string | null;
  completionTimeSeconds: number | null;
  createdAt: string;
}

export interface SubmitAssessmentInput {
  responses: RiskQuestionnaireResponse[];
  completionTimeSeconds?: number;
}

export interface RiskStatistics {
  conservative: number;
  moderate: number;
  aggressive: number;
}

export interface RiskRecommendation {
  agent: TradingAgent;
  agentName: string;
  agentDescription: string;
  riskProfile: RiskProfile;
  suggestedAllocation: {
    stocks: number;
    bonds: number;
    crypto: number;
    cash: number;
  };
  expectedReturn: {
    min: number;
    max: number;
  };
  maxDrawdown: number;
}

// ============================================================================
// API Functions
// ============================================================================

/**
 * Get all risk questionnaire questions
 */
export async function getQuestions(): Promise<RiskQuestion[]> {
  const response = await fetch(`${API_URL}/api/v1/risk/questions`, {
    credentials: 'include',
  });
  if (!response.ok) throw new Error('Failed to fetch risk questions');
  const data = await response.json();
  return data.data || data;
}

/**
 * Submit risk assessment responses
 */
export async function submitAssessment(input: SubmitAssessmentInput): Promise<RiskAssessment> {
  const response = await fetch(`${API_URL}/api/v1/risk/assessment`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    credentials: 'include',
    body: JSON.stringify(input),
  });
  if (!response.ok) {
    const error = await response.json().catch(() => ({}));
    throw new Error(error.message || 'Failed to submit risk assessment');
  }
  const data = await response.json();
  return data.data || data;
}

/**
 * Get current user's most recent risk assessment
 */
export async function getCurrentAssessment(): Promise<RiskAssessment | null> {
  const response = await fetch(`${API_URL}/api/v1/risk/assessment`, {
    credentials: 'include',
  });
  if (response.status === 404) return null;
  if (!response.ok) throw new Error('Failed to fetch risk assessment');
  const data = await response.json();
  return data.data || data;
}

/**
 * Get risk profile for a specific user (admin)
 */
export async function getProfile(userId: string): Promise<RiskAssessment | null> {
  const response = await fetch(`${API_URL}/api/v1/risk/assessment/${userId}`, {
    credentials: 'include',
  });
  if (response.status === 404) return null;
  if (!response.ok) throw new Error('Failed to fetch user risk profile');
  const data = await response.json();
  return data.data || data;
}

/**
 * Check if current user has a valid (non-expired) assessment
 */
export async function checkValidAssessment(): Promise<boolean> {
  const response = await fetch(`${API_URL}/api/v1/risk/assessment/valid`, {
    credentials: 'include',
  });
  if (!response.ok) throw new Error('Failed to check assessment validity');
  const data = await response.json();
  return data.data?.isValid ?? data.isValid ?? false;
}

/**
 * Get assessment history for current user
 */
export async function getAssessmentHistory(): Promise<RiskAssessment[]> {
  const response = await fetch(`${API_URL}/api/v1/risk/assessment/history`, {
    credentials: 'include',
  });
  if (!response.ok) throw new Error('Failed to fetch assessment history');
  const data = await response.json();
  return data.data || data;
}

/**
 * Get risk profile statistics (public)
 */
export async function getStatistics(): Promise<RiskStatistics> {
  const response = await fetch(`${API_URL}/api/v1/risk/statistics`, {
    credentials: 'include',
  });
  if (!response.ok) throw new Error('Failed to fetch risk statistics');
  const data = await response.json();
  return data.data || data;
}

/**
 * Get recommendations based on risk profile
 */
export function getRecommendations(riskProfile: RiskProfile): RiskRecommendation {
  const recommendations: Record<RiskProfile, RiskRecommendation> = {
    conservative: {
      agent: 'atlas',
      agentName: 'Atlas',
      agentDescription: 'Conservative trading agent focused on capital preservation and steady returns',
      riskProfile: 'conservative',
      suggestedAllocation: {
        stocks: 20,
        bonds: 50,
        crypto: 5,
        cash: 25,
      },
      expectedReturn: {
        min: 3,
        max: 6,
      },
      maxDrawdown: 10,
    },
    moderate: {
      agent: 'orion',
      agentName: 'Orion',
      agentDescription: 'Balanced trading agent optimizing risk-adjusted returns',
      riskProfile: 'moderate',
      suggestedAllocation: {
        stocks: 45,
        bonds: 30,
        crypto: 15,
        cash: 10,
      },
      expectedReturn: {
        min: 7,
        max: 12,
      },
      maxDrawdown: 20,
    },
    aggressive: {
      agent: 'nova',
      agentName: 'Nova',
      agentDescription: 'Aggressive trading agent seeking maximum growth opportunities',
      riskProfile: 'aggressive',
      suggestedAllocation: {
        stocks: 50,
        bonds: 10,
        crypto: 35,
        cash: 5,
      },
      expectedReturn: {
        min: 15,
        max: 30,
      },
      maxDrawdown: 40,
    },
  };

  return recommendations[riskProfile];
}
