File size: 7,088 Bytes
91d209c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66e744c
 
91d209c
 
 
 
 
 
 
 
 
 
 
 
 
66e744c
 
 
91d209c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66e744c
 
 
 
 
 
91d209c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66e744c
 
 
91d209c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66e744c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91d209c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import React, { createContext, useContext, useReducer, ReactNode } from 'react';
import type { 
  GenerationState, 
  GenerationStep, 
  VideoProvider, 
  VeoSegment, 
  GeneratedVideo 
} from '@/types';

// Initial state
const initialState: GenerationState = {
  step: 'idle',
  provider: null,
  segments: [],
  currentSegmentIndex: 0,
  generatedVideos: [],
  progress: {
    current: 0,
    total: 0,
    message: '',
  },
  error: null,
  taskId: null,
  retryState: null,
  activeTaskIds: [] as string[],
  isCancelling: false,
};

// Action types
type GenerationAction =
  | { type: 'SET_PROVIDER'; payload: VideoProvider }
  | { type: 'SET_STEP'; payload: GenerationStep }
  | { type: 'SET_SEGMENTS'; payload: VeoSegment[] }
  | { type: 'SET_CURRENT_SEGMENT'; payload: number }
  | { type: 'ADD_GENERATED_VIDEO'; payload: GeneratedVideo }
  | { type: 'SET_PROGRESS'; payload: { current?: number; total?: number; message?: string } }
  | { type: 'SET_ERROR'; payload: string | null }
  | { type: 'SET_TASK_ID'; payload: string | null }
  | { type: 'SET_RETRY_STATE'; payload: { failedSegmentIndex: number; error: string } | null }
  | { type: 'ADD_TASK_ID'; payload: string }
  | { type: 'REMOVE_TASK_ID'; payload: string }
  | { type: 'SET_CANCELLING'; payload: boolean }
  | { type: 'RESET' };

// Reducer
function generationReducer(state: GenerationState, action: GenerationAction): GenerationState {
  switch (action.type) {
    case 'SET_PROVIDER':
      return { ...state, provider: action.payload };
    case 'SET_STEP':
      return { ...state, step: action.payload };
    case 'SET_SEGMENTS':
      return { ...state, segments: action.payload };
    case 'SET_CURRENT_SEGMENT':
      return { ...state, currentSegmentIndex: action.payload };
    case 'ADD_GENERATED_VIDEO':
      return { 
        ...state, 
        generatedVideos: [...state.generatedVideos, action.payload] 
      };
    case 'SET_PROGRESS':
      return { 
        ...state, 
        progress: { ...state.progress, ...action.payload } 
      };
    case 'SET_ERROR':
      return { ...state, error: action.payload, step: action.payload ? 'error' : state.step };
    case 'SET_TASK_ID':
      return { ...state, taskId: action.payload };
    case 'SET_RETRY_STATE':
      return { ...state, retryState: action.payload };
    case 'ADD_TASK_ID':
      return { ...state, activeTaskIds: [...state.activeTaskIds, action.payload] };
    case 'REMOVE_TASK_ID':
      return { ...state, activeTaskIds: state.activeTaskIds.filter(id => id !== action.payload) };
    case 'SET_CANCELLING':
      return { ...state, isCancelling: action.payload };
    case 'RESET':
      return { ...initialState, provider: state.provider };
    default:
      return state;
  }
}

// Context
interface GenerationContextValue {
  state: GenerationState;
  dispatch: React.Dispatch<GenerationAction>;
  
  // Helper actions
  selectProvider: (provider: VideoProvider) => void;
  setStep: (step: GenerationStep) => void;
  startGeneration: (segments: VeoSegment[]) => void;
  advanceSegment: () => void;
  addVideo: (video: GeneratedVideo) => void;
  updateProgress: (message: string, current?: number, total?: number) => void;
  setError: (error: string | null) => void;
  setRetryState: (state: { failedSegmentIndex: number; error: string } | null) => void;
  updateSegments: (segments: VeoSegment[]) => void;
  addTaskId: (taskId: string) => void;
  removeTaskId: (taskId: string) => void;
  cancelGeneration: () => Promise<void>;
  reset: () => void;
}

const GenerationContext = createContext<GenerationContextValue | null>(null);

// Provider component
export function GenerationProvider({ children }: { children: ReactNode }) {
  const [state, dispatch] = useReducer(generationReducer, initialState);

  const value: GenerationContextValue = {
    state,
    dispatch,
    
    selectProvider: (provider) => {
      dispatch({ type: 'SET_PROVIDER', payload: provider });
      dispatch({ type: 'SET_STEP', payload: 'configuring' });
    },
    
    setStep: (step) => {
      dispatch({ type: 'SET_STEP', payload: step });
    },
    
    startGeneration: (segments) => {
      dispatch({ type: 'SET_SEGMENTS', payload: segments });
      dispatch({ type: 'SET_CURRENT_SEGMENT', payload: 0 });
      dispatch({ type: 'SET_PROGRESS', payload: { current: 0, total: segments.length, message: 'Starting generation...' } });
      dispatch({ type: 'SET_STEP', payload: 'generating_video' });
    },
    
    advanceSegment: () => {
      const nextIndex = state.currentSegmentIndex + 1;
      dispatch({ type: 'SET_CURRENT_SEGMENT', payload: nextIndex });
      dispatch({ type: 'SET_PROGRESS', payload: { current: nextIndex } });
    },
    
    addVideo: (video) => {
      dispatch({ type: 'ADD_GENERATED_VIDEO', payload: video });
    },
    
    updateProgress: (message, current, total) => {
      dispatch({ 
        type: 'SET_PROGRESS', 
        payload: { 
          message, 
          ...(current !== undefined && { current }), 
          ...(total !== undefined && { total }) 
        } 
      });
    },
    
    setError: (error) => {
      dispatch({ type: 'SET_ERROR', payload: error });
    },
    
    setRetryState: (retryState) => {
      dispatch({ type: 'SET_RETRY_STATE', payload: retryState });
    },

    updateSegments: (segments) => {
      dispatch({ type: 'SET_SEGMENTS', payload: segments });
    },

    addTaskId: (taskId) => {
      dispatch({ type: 'ADD_TASK_ID', payload: taskId });
    },

    removeTaskId: (taskId) => {
      dispatch({ type: 'REMOVE_TASK_ID', payload: taskId });
    },

    cancelGeneration: async () => {
      dispatch({ type: 'SET_CANCELLING', payload: true });
      try {
        const { klingCancel } = await import('@/utils/api');
        // Cancel all active tasks
        const currentTaskIds = [...state.activeTaskIds];
        const cancelPromises = currentTaskIds.map(taskId => 
          klingCancel(taskId).catch(err => {
            console.warn(`Failed to cancel task ${taskId}:`, err);
          })
        );
        await Promise.all(cancelPromises);
        // Clear all task IDs
        currentTaskIds.forEach(id => {
          dispatch({ type: 'REMOVE_TASK_ID', payload: id });
        });
        dispatch({ type: 'SET_TASK_ID', payload: null });
        dispatch({ type: 'SET_ERROR', payload: 'Generation cancelled by user' });
        dispatch({ type: 'SET_STEP', payload: 'error' });
      } catch (error) {
        console.error('Error cancelling generation:', error);
        dispatch({ type: 'SET_ERROR', payload: 'Failed to cancel generation' });
      } finally {
        dispatch({ type: 'SET_CANCELLING', payload: false });
      }
    },

    reset: () => {
      dispatch({ type: 'RESET' });
    },
  };

  return (
    <GenerationContext.Provider value={value}>
      {children}
    </GenerationContext.Provider>
  );
}

// Hook
export function useGeneration() {
  const context = useContext(GenerationContext);
  if (!context) {
    throw new Error('useGeneration must be used within GenerationProvider');
  }
  return context;
}