import { z } from 'zod';

/**
 * MCP Resource types for user context
 */

/**
 * Base resource structure from MCP server
 */
export const MCPResourceSchema = z.object({
  uri: z.string(),
  mimeType: z.string().optional(),
  text: z.string().optional(),
  blob: z.string().optional(), // base64 encoded
});

export type MCPResource = z.infer<typeof MCPResourceSchema>;

/**
 * User profile context
 */
export const UserProfileContextSchema = z.object({
  tradingExperience: z.enum(['beginner', 'intermediate', 'advanced', 'professional']),
  preferredTimeframes: z.array(z.string()),
  riskTolerance: z.enum(['low', 'medium', 'high']),
  tradingStyle: z.string(),
  favoriteIndicators: z.array(z.string()).optional(),
  activeTradingPairs: z.array(z.string()).optional(),
  notes: z.string().optional(),
});

export type UserProfileContext = z.infer<typeof UserProfileContextSchema>;

/**
 * Workspace state (current chart, positions, etc.)
 */
export const WorkspaceStateSchema = z.object({
  currentChart: z.object({
    ticker: z.string(),
    timeframe: z.string(),
    indicators: z.array(z.string()).optional(),
  }).optional(),
  watchlist: z.array(z.string()),
  openPositions: z.array(z.object({
    ticker: z.string(),
    side: z.enum(['long', 'short']),
    size: z.number(),
    entryPrice: z.number(),
    currentPrice: z.number().optional(),
    unrealizedPnL: z.number().optional(),
  })),
  recentAlerts: z.array(z.object({
    type: z.string(),
    message: z.string(),
    timestamp: z.string(),
  })).optional(),
});

export type WorkspaceState = z.infer<typeof WorkspaceStateSchema>;

/**
 * Standard context resource URIs
 */
export const CONTEXT_URIS = {
  USER_PROFILE: 'context://user-profile',
  CONVERSATION_SUMMARY: 'context://conversation-summary',
  WORKSPACE_STATE: 'context://workspace-state',
  SYSTEM_PROMPT: 'context://system-prompt',
} as const;

/**
 * Resource content interface
 */
export interface ResourceContent {
  uri: string;
  mimeType?: string;
  text?: string;
  blob?: string;
}

/**
 * Helper to parse resource content
 */
export function parseResource<T>(resource: ResourceContent, schema: z.ZodSchema<T>): T | null {
  if (!resource.text) {
    return null;
  }

  try {
    // Try JSON parsing if mime type is JSON
    if (resource.mimeType?.includes('json')) {
      const data = JSON.parse(resource.text);
      return schema.parse(data);
    }

    // Otherwise return as-is for text resources
    return resource.text as T;
  } catch {
    return null;
  }
}
