console.log('🔍 SCHEMA FILE: Starting schema file execution');

import { createTLSchema, defaultShapeSchemas, defaultBindingSchemas } from '@tldraw/tlschema';
import { createTLSchemaFromUtils, defaultBindingUtils, defaultShapeUtils } from '@tldraw/tldraw';
import { ShapeUtils } from './shapes';
import { allBindingUtils } from './bindings';
import { ccGraphShapeProps } from './cc-base/cc-graph/cc-graph-props';
import { ccGraphMigrations } from './cc-base/cc-graph/cc-graph-migrations';
import { GraphShapeType } from './cc-base/cc-graph/cc-graph-types';

// Create schema with shape definitions
const customShapes = {
    ...defaultShapeSchemas,
    // Dynamically generate shape schemas from ShapeUtils
    ...Object.values(ShapeUtils).reduce((acc, util) => ({
        ...acc,
        [util.type]: {
            props: util.props,
            migrations: util.migrations,
        }
    }), {}),
    // Add graph shapes
    ...(ccGraphShapeProps ? Object.entries(ccGraphShapeProps).reduce((acc, [type, props]) => ({
        ...acc,
        [type]: {
            props,
            migrations: ccGraphMigrations[type as GraphShapeType],
        }
    }), {}) : {})
};

// Debug: Log the custom shapes being added
console.log('🔍 SCHEMA DEBUG: Custom shapes in schema:', Object.keys(customShapes).filter(key => key.startsWith('cc-')));
console.log('🔍 SCHEMA DEBUG: ShapeUtils types:', Object.values(ShapeUtils).map(util => util.type));
console.log('🔍 SCHEMA DEBUG: ccGraphShapeProps types:', Object.keys(ccGraphShapeProps || {}));

export const customSchema = createTLSchema({
    shapes: customShapes,
    bindings: {
        ...defaultBindingSchemas,
        // Add binding schemas from our custom binding utils
        ...allBindingUtils.reduce((acc, util) => ({
            ...acc,
            [util.type]: {
                props: util.props,
                migrations: util.migrations,
            }
        }), {})
    },
});

// Debug: Log the final schema sequences
console.log('🔍 SCHEMA DEBUG: Final schema sequences:', customSchema.serialize().sequences);
console.log('🔍 SCHEMA DEBUG: Custom shape sequences:', Object.keys(customSchema.serialize().sequences).filter(key => key.includes('cc-')));

// Create schema from utils (alternative approach)
export const schemaFromUtils = createTLSchemaFromUtils({
    shapeUtils: [
        ...defaultShapeUtils,
        ...Object.values(ShapeUtils)
    ],
    bindingUtils: [
        ...defaultBindingUtils,
        ...allBindingUtils
    ],
});