"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.useModelVersions = exports.useModelDeployment = exports.useModelRegistry = exports.ModelRegistryProvider = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = __importStar(require("react"));
const api_js_1 = require("../../services/api.js");
// Initial state
const initialState = {
    models: [],
    loading: false,
    error: null,
    filters: {},
    sortOptions: {
        field: 'created_at',
        direction: 'desc'
    },
    selectedModel: null
};
// Reducer function
const modelRegistryReducer = (state, action) => {
    switch (action.type) {
        case 'FETCH_MODELS_START':
        case 'CREATE_MODEL_START':
            return {
                ...state,
                loading: true,
                error: null
            };
        case 'FETCH_MODELS_SUCCESS':
            return {
                ...state,
                loading: false,
                models: action.payload,
                error: null
            };
        case 'FETCH_MODELS_ERROR':
        case 'CREATE_MODEL_ERROR':
            return {
                ...state,
                loading: false,
                error: action.payload
            };
        case 'CREATE_MODEL_SUCCESS':
            return {
                ...state,
                loading: false,
                models: [...state.models, action.payload],
                error: null
            };
        case 'UPDATE_MODEL_SUCCESS':
            return {
                ...state,
                models: state.models.map(model => model.id === action.payload.id ? action.payload : model),
                selectedModel: state.selectedModel?.id === action.payload.id ? action.payload : state.selectedModel
            };
        case 'DELETE_MODEL_SUCCESS':
            return {
                ...state,
                models: state.models.filter(model => model.id !== action.payload),
                selectedModel: state.selectedModel?.id === action.payload ? null : state.selectedModel
            };
        case 'SET_FILTERS':
            return {
                ...state,
                filters: { ...state.filters, ...action.payload }
            };
        case 'SET_SORT_OPTIONS':
            return {
                ...state,
                sortOptions: action.payload
            };
        case 'SELECT_MODEL':
            return {
                ...state,
                selectedModel: action.payload
            };
        case 'CLEAR_ERROR':
            return {
                ...state,
                error: null
            };
        default:
            return state;
    }
};
// Create context
const ModelRegistryContext = (0, react_1.createContext)(null);
// Provider component
const ModelRegistryProvider = ({ children }) => {
    const [state, dispatch] = (0, react_1.useReducer)(modelRegistryReducer, initialState);
    // Fetch models with optional filters
    const fetchModels = (0, react_1.useCallback)(async (filters) => {
        dispatch({ type: 'FETCH_MODELS_START' });
        try {
            const response = await api_js_1.modelRegistryApi.getModels(filters);
            dispatch({ type: 'FETCH_MODELS_SUCCESS', payload: response.models });
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : 'Failed to fetch models';
            dispatch({ type: 'FETCH_MODELS_ERROR', payload: errorMessage });
        }
    }, []);
    // Create new model
    const createModel = (0, react_1.useCallback)(async (data) => {
        dispatch({ type: 'CREATE_MODEL_START' });
        try {
            const response = await api_js_1.modelRegistryApi.createModel(data);
            dispatch({ type: 'CREATE_MODEL_SUCCESS', payload: response.model });
            return response.model;
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : 'Failed to create model';
            dispatch({ type: 'CREATE_MODEL_ERROR', payload: errorMessage });
            throw error;
        }
    }, []);
    // Update existing model
    const updateModel = (0, react_1.useCallback)(async (data) => {
        try {
            const response = await api_js_1.modelRegistryApi.updateModel(data);
            dispatch({ type: 'UPDATE_MODEL_SUCCESS', payload: response.model });
            return response.model;
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : 'Failed to update model';
            dispatch({ type: 'CREATE_MODEL_ERROR', payload: errorMessage });
            throw error;
        }
    }, []);
    // Delete model
    const deleteModel = (0, react_1.useCallback)(async (modelId) => {
        try {
            await api_js_1.modelRegistryApi.deleteModel(modelId);
            dispatch({ type: 'DELETE_MODEL_SUCCESS', payload: modelId });
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : 'Failed to delete model';
            dispatch({ type: 'CREATE_MODEL_ERROR', payload: errorMessage });
            throw error;
        }
    }, []);
    // Deploy model
    const deployModel = (0, react_1.useCallback)(async (data) => {
        try {
            const response = await api_js_1.modelRegistryApi.deployModel(data);
            return response;
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : 'Failed to deploy model';
            dispatch({ type: 'CREATE_MODEL_ERROR', payload: errorMessage });
            throw error;
        }
    }, []);
    // Rollback model
    const rollbackModel = (0, react_1.useCallback)(async (data) => {
        try {
            const response = await api_js_1.modelRegistryApi.rollbackModel(data.model_id, data.target_version);
            return response;
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : 'Failed to rollback model';
            dispatch({ type: 'CREATE_MODEL_ERROR', payload: errorMessage });
            throw error;
        }
    }, []);
    // Get model versions
    const getModelVersions = (0, react_1.useCallback)(async (modelId) => {
        try {
            const response = await api_js_1.modelRegistryApi.getModelVersions(modelId);
            return response.versions;
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : 'Failed to fetch model versions';
            dispatch({ type: 'CREATE_MODEL_ERROR', payload: errorMessage });
            throw error;
        }
    }, []);
    // Set filters
    const setFilters = (0, react_1.useCallback)((filters) => {
        dispatch({ type: 'SET_FILTERS', payload: filters });
    }, []);
    // Set sort options
    const setSortOptions = (0, react_1.useCallback)((options) => {
        dispatch({ type: 'SET_SORT_OPTIONS', payload: options });
    }, []);
    // Select model
    const selectModel = (0, react_1.useCallback)((model) => {
        dispatch({ type: 'SELECT_MODEL', payload: model });
    }, []);
    // Clear error
    const clearError = (0, react_1.useCallback)(() => {
        dispatch({ type: 'CLEAR_ERROR' });
    }, []);
    // Auto-fetch models on mount
    (0, react_1.useEffect)(() => {
        fetchModels();
    }, [fetchModels]);
    // Re-fetch when filters or sort options change
    (0, react_1.useEffect)(() => {
        if (Object.keys(state.filters).length > 0) {
            fetchModels(state.filters);
        }
    }, [state.filters, fetchModels]);
    // Context value
    const contextValue = {
        models: state.models,
        loading: state.loading,
        error: state.error,
        filters: state.filters,
        sortOptions: state.sortOptions,
        selectedModel: state.selectedModel,
        fetchModels,
        createModel,
        updateModel,
        deleteModel,
        deployModel,
        rollbackModel,
        getModelVersions,
        setFilters,
        setSortOptions,
        selectModel,
        clearError
    };
    return ((0, jsx_runtime_1.jsx)(ModelRegistryContext.Provider, { value: contextValue, children: children }));
};
exports.ModelRegistryProvider = ModelRegistryProvider;
// Custom hook to use the context
const useModelRegistry = () => {
    const context = (0, react_1.useContext)(ModelRegistryContext);
    if (!context) {
        throw new Error('useModelRegistry must be used within a ModelRegistryProvider');
    }
    return context;
};
exports.useModelRegistry = useModelRegistry;
// Custom hook for model deployment operations
const useModelDeployment = () => {
    const [deploymentState, setDeploymentState] = react_1.default.useState({
        deployment: null,
        loading: false,
        error: null
    });
    const deploy = (0, react_1.useCallback)(async (data) => {
        setDeploymentState(prev => ({ ...prev, loading: true, error: null }));
        try {
            const response = await api_js_1.modelRegistryApi.deployModel(data);
            setDeploymentState({
                deployment: response,
                loading: false,
                error: null
            });
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : 'Deployment failed';
            setDeploymentState({
                deployment: null,
                loading: false,
                error: errorMessage
            });
        }
    }, []);
    const checkStatus = (0, react_1.useCallback)(async (deploymentId) => {
        try {
            const response = await api_js_1.modelRegistryApi.getDeploymentStatus(deploymentId);
            setDeploymentState(prev => ({ ...prev, deployment: response }));
            return response;
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : 'Failed to check deployment status';
            setDeploymentState(prev => ({ ...prev, error: errorMessage }));
            throw error;
        }
    }, []);
    const cancel = (0, react_1.useCallback)(async (deploymentId) => {
        try {
            await api_js_1.modelRegistryApi.cancelDeployment(deploymentId);
            setDeploymentState(prev => ({
                ...prev,
                deployment: prev.deployment ? { ...prev.deployment, status: 'failed' } : null
            }));
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : 'Failed to cancel deployment';
            setDeploymentState(prev => ({ ...prev, error: errorMessage }));
            throw error;
        }
    }, []);
    const clearError = (0, react_1.useCallback)(() => {
        setDeploymentState(prev => ({ ...prev, error: null }));
    }, []);
    return {
        ...deploymentState,
        deploy,
        checkStatus,
        cancel,
        clearError
    };
};
exports.useModelDeployment = useModelDeployment;
// Custom hook for model versions management
const useModelVersions = (modelId) => {
    const [versionState, setVersionState] = react_1.default.useState({
        versions: [],
        loading: false,
        error: null
    });
    const fetchVersions = (0, react_1.useCallback)(async (id) => {
        setVersionState(prev => ({ ...prev, loading: true, error: null }));
        try {
            const response = await api_js_1.modelRegistryApi.getModelVersions(id);
            setVersionState({
                versions: response.versions,
                loading: false,
                error: null
            });
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : 'Failed to fetch versions';
            setVersionState({
                versions: [],
                loading: false,
                error: errorMessage
            });
        }
    }, []);
    const rollback = (0, react_1.useCallback)(async (data) => {
        try {
            await api_js_1.modelRegistryApi.rollbackModel(data.model_id, data.target_version);
            // Refresh versions after rollback
            if (modelId) {
                await fetchVersions(modelId);
            }
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : 'Rollback failed';
            setVersionState(prev => ({ ...prev, error: errorMessage }));
            throw error;
        }
    }, [modelId, fetchVersions]);
    const clearError = (0, react_1.useCallback)(() => {
        setVersionState(prev => ({ ...prev, error: null }));
    }, []);
    // Auto-fetch versions when modelId changes
    (0, react_1.useEffect)(() => {
        if (modelId) {
            fetchVersions(modelId);
        }
    }, [modelId, fetchVersions]);
    return {
        ...versionState,
        fetchVersions,
        rollback,
        clearError
    };
};
exports.useModelVersions = useModelVersions;
//# sourceMappingURL=ModelRegistryProvider.js.map