<?php

/**
 * Create Content Model Tool
 * Allows the AI to create new content models (collections, singletons, trees)
 */


if (!$app->module('content')) {
    return false;
}

return [
    'name' => 'createContentModel',
    'description' => 'Create a new content model (collection, singleton, or tree) with specified fields.',
    'parameters' => [
        'type' => 'object',
        'properties' => [
            'name' => [
                'type' => 'string',
                'description' => 'Unique model name (e.g., "blogposts"). Use alphanumeric characters only (no underscores/hyphens).'
            ],
            'label' => [
                'type' => 'string',
                'description' => 'Human-readable label for the model (e.g., "Blog Posts").'
            ],
            'type' => [
                'type' => 'string',
                'description' => 'Type of the model.',
                'enum' => ['collection', 'singleton', 'tree'],
                'default' => 'collection'
            ],
            'group' => [
                'type' => 'string',
                'description' => 'Group name to organize models (e.g., "Content", "Settings").'
            ],
            'info' => [
                'type' => 'string',
                'description' => 'Description or purpose of the model.'
            ],
            'fields' => [
                'type' => 'array',
                'description' => 'List of fields. You should infer the correct "type" and "multiple" status based on the field name (e.g., "slides" -> type: "set", multiple: true; "gallery" -> type: "asset", multiple: true).',
                'items' => [
                    'type' => 'object',
                    'properties' => [
                        'name' => [
                            'type' => 'string',
                            'description' => 'Field name (e.g., "title", "slides").'
                        ],
                        'type' => [
                            'type' => 'string',
                            'description' => 'Field type. Infer "set" for complex items (like slides with image+text).',
                            'enum' => [
                                'text', 'boolean', 'code', 'color', 'date', 'datetime',
                                'nav', 'number', 'object', 'select', 'set', 'table',
                                'tags', 'time', 'wysiwyg', 'asset', 'contentItemLink', 'layout',
                                'component', 'pageUrl', 'seo'
                            ],
                            'default' => 'text'
                        ],
                        'label' => [
                            'type' => 'string',
                            'description' => 'Field label.'
                        ],
                        'options' => [
                            'type' => 'object',
                            'description' => 'Specific options for the field type. Examples:
- set: {"fields": [{"name": "subfield", "type": "text"}], "display": "${data.fieldname}"}
- select: {"options": ["Option A", "Option B"]}
- table: {"columns": [{"name": "col1"}, {"name": "col2"}]}
- asset: {"filter": "{\"type\": \"image\"}"}
- contentItemLink: {"link": "model_name", "display": "${data.title}"}
- layout: {"allowedComponents": ["image", "text", "section", "grid"]}
- code: {"mode": "html", "height": 200}
- text: {"multiline": true, "showCount": true, "maxlength": 140}
- gallery: use "asset" type with "multiple": true'
                        ],
                        'required' => [
                            'type' => 'boolean',
                            'description' => 'Whether the field is required.',
                            'default' => false
                        ],
                        'multiple' => [
                            'type' => 'boolean',
                            'description' => 'Set to TRUE if the field name is plural or implies a list (e.g., "slides", "tags", "images").',
                            'default' => false
                        ],
                        'i18n' => [
                            'type' => 'boolean',
                            'description' => 'Whether the field can be localized.',
                            'default' => false
                        ],
                        'condition' => [
                            'type' => 'string',
                            'description' => 'Conditional logic to show/hide the field (e.g., "data.type == \'post\'").'
                        ]
                    ],
                    'required' => ['name', 'type']
                ]
            ]
        ],
        'required' => ['name', 'type'],
        'additionalProperties' => false
    ],
    'handler' => function($args, $app) {

        $name = $args['name'];

        // Sanitize name
        $name = preg_replace('/[^a-zA-Z0-9]/', '', $name);

        if (!$name) {
            return ['error' => 'Invalid model name.'];
        }

        // Check if exists
        if ($app->module('content')->exists($name)) {
            return ['error' => "Content model '{$name}' already exists."];
        }

        $data = [
            'label' => $args['label'] ?? $name,
            'type' => $args['type'] ?? 'collection',
            'group' => $args['group'] ?? '',
            'info' => $args['info'] ?? '',
            'fields' => $args['fields'] ?? []
        ];

        // Process fields to ensure correct structure
        $fields = $args['fields'] ?? [];
        $formattedFields = [];

        if (!empty($fields)) {
            foreach ($fields as $field) {
                // Ensure options is an array
                if (isset($field['options']) && !is_array($field['options'])) {
                    $field['options'] = [];
                }

                $fieldData = array_merge([
                    'type' => 'text',
                    'label' => $field['name'],
                    'options' => [],
                    'required' => false,
                    'multiple' => false,
                    'i18n' => false,
                    'condition' => $field['condition'] ?? ''
                ], $field);

                $formattedFields[] = $fieldData;
            }
            $data['fields'] = $formattedFields;
        }

        try {


            $model = $app->module('content')->createModel($name, $data);

            if (!$model) {
                return [
                    'error' => "Failed to create model '{$name}'."
                ];
            }

            return [
                'success' => true,
                'message' => "Content model '{$name}' created successfully.",
                'model' => [
                    'name' => $model['name'],
                    'label' => $model['label'],
                    'type' => $model['type'],
                    'field_count' => count($model['fields'])
                ]
            ];

        } catch (\Throwable $e) {
            return [
                'error' => "Exception occurred: " . $e->getMessage()
            ];
        }
    },
    'options' => [
        'permission' => 'content/:models/manage'
    ]
];
