/**
 * Composable: useShadowRuns
 * TanStack Query integration for shadow run data fetching
 */

import { useQuery, useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/vue-query'
import type { UseQueryReturnType, UseInfiniteQueryReturnType } from '@tanstack/vue-query'
import { ref } from 'vue'

export interface ShadowRun {
  runId: string
  modelName: string
  windowStart: string
  windowEnd: string
  tradingDays: number
  totalReturn: number
  sharpeRatio: number
  pbo: number
  dsr: number
  oos: number
  status: 'pending' | 'running' | 'completed' | 'failed'
  createdAt: string
}

export interface ShadowRunDetail extends ShadowRun {
  maxDrawdown: number
  winRate: number
  profitFactor: number
  phases: {
    bull: { return: number; sharpe: number; trades: number }
    bear: { return: number; sharpe: number; trades: number }
    sideways: { return: number; sharpe: number; trades: number }
  }
}

export interface ShadowRunListParams {
  page?: number
  pageSize?: number
  search?: string
  status?: string
  dateStart?: string
  dateEnd?: string
}

export interface ShadowRunListResponse {
  items: ShadowRun[]
  total: number
  page: number
  pageSize: number
}

// Mock API client (replace with actual API calls)
const apiClient = {
  async listShadowRuns(params: ShadowRunListParams): Promise<ShadowRunListResponse> {
    // Simulate API delay
    await new Promise(resolve => setTimeout(resolve, 300))

    // Mock data
    const items: ShadowRun[] = [
      {
        runId: '00000000-0000-0000-0000-000000000001',
        modelName: 'Alpha Strategy',
        windowStart: '2024-01-02',
        windowEnd: '2024-09-10',
        tradingDays: 187,
        totalReturn: 12.5,
        sharpeRatio: 1.8,
        pbo: 15.2,
        dsr: 96.5,
        oos: 1.8,
        status: 'completed',
        createdAt: '2026-08-01',
      },
      {
        runId: '00000000-0000-0000-0000-000000000002',
        modelName: 'Beta Model',
        windowStart: '2024-01-02',
        windowEnd: '2024-09-10',
        tradingDays: 187,
        totalReturn: -2.3,
        sharpeRatio: -0.5,
        pbo: 42.1,
        dsr: 45.2,
        oos: 3.2,
        status: 'completed',
        createdAt: '2026-08-02',
      },
    ]

    return {
      items: items.slice(0, params.pageSize || 50),
      total: items.length,
      page: params.page || 1,
      pageSize: params.pageSize || 50,
    }
  },

  async getShadowRunDetail(runId: string): Promise<ShadowRunDetail> {
    await new Promise(resolve => setTimeout(resolve, 200))

    return {
      runId,
      modelName: 'Alpha Strategy',
      windowStart: '2024-01-02',
      windowEnd: '2024-09-10',
      tradingDays: 187,
      totalReturn: 12.5,
      sharpeRatio: 1.8,
      pbo: 15.2,
      dsr: 96.5,
      oos: 1.8,
      maxDrawdown: -8.3,
      winRate: 58.5,
      profitFactor: 2.1,
      phases: {
        bull: { return: 18.2, sharpe: 2.3, trades: 45 },
        bear: { return: -2.1, sharpe: -0.5, trades: 28 },
        sideways: { return: 5.3, sharpe: 1.1, trades: 32 },
      },
      status: 'completed',
      createdAt: '2026-08-01',
    }
  },

  async createShadowRun(data: { modelId: string; windowStart: string; windowEnd: string }) {
    await new Promise(resolve => setTimeout(resolve, 500))
    return { runId: '00000000-0000-0000-0000-000000000099', ...data }
  },
}

// Query key factories
export const shadowRunQueryKeys = {
  all: ['shadowRuns'] as const,
  lists: () => [...shadowRunQueryKeys.all, 'list'] as const,
  list: (params: ShadowRunListParams) => [...shadowRunQueryKeys.lists(), params] as const,
  details: () => [...shadowRunQueryKeys.all, 'detail'] as const,
  detail: (runId: string) => [...shadowRunQueryKeys.details(), runId] as const,
}

/**
 * Fetch list of shadow runs with pagination
 */
export function useShadowRunsList(params: ShadowRunListParams = {}) {
  return useQuery({
    queryKey: shadowRunQueryKeys.list(params),
    queryFn: () => apiClient.listShadowRuns(params),
    staleTime: 5 * 60 * 1000, // 5 minutes
    gcTime: 10 * 60 * 1000, // 10 minutes
  })
}

/**
 * Fetch single shadow run detail
 */
export function useShadowRunDetail(runId: string) {
  return useQuery({
    queryKey: shadowRunQueryKeys.detail(runId),
    queryFn: () => apiClient.getShadowRunDetail(runId),
    enabled: !!runId,
    staleTime: 5 * 60 * 1000,
    gcTime: 10 * 60 * 1000,
  })
}

/**
 * Create a new shadow run (mutation)
 */
export function useCreateShadowRun() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (data: { modelId: string; windowStart: string; windowEnd: string }) =>
      apiClient.createShadowRun(data),
    onSuccess: () => {
      // Invalidate and refetch list
      queryClient.invalidateQueries({ queryKey: shadowRunQueryKeys.lists() })
    },
  })
}

/**
 * Refetch shadow run list
 */
export function useRefreshShadowRuns() {
  const queryClient = useQueryClient()

  return async () => {
    await queryClient.refetchQueries({ queryKey: shadowRunQueryKeys.lists() })
  }
}
