<?php
/**
 * Admin autonomy tools for the Niwa template/snippet library.
 *
 * @package Niwa_AI
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

trait Niwa_AI_Tools_Template_Library {
	private function template_library_repositories() {
		return array(
			'templates'  => new Niwa_AI_Template_Repository(),
			'snippets'   => new Niwa_AI_Snippet_Repository(),
			'generator'  => new Niwa_AI_Template_AI_Generator( $this->eval_openai_client, $this->eval_auth_manager, $this->eval_model_router, new Niwa_AI_Template_Elementor_Builder() ),
			'elementor_builder' => new Niwa_AI_Template_Elementor_Builder(),
			'validator'  => new Niwa_AI_Snippet_Validator(),
			'filesystem' => new Niwa_AI_Snippet_Filesystem(),
		);
	}

	private function execute_template_library_list( $args ) {
		$repos = $this->template_library_repositories();
		$type  = isset( $args['type'] ) ? sanitize_key( (string) $args['type'] ) : '';
		$limit = isset( $args['limit'] ) ? intval( $args['limit'] ) : 40;

		return array(
			'success'          => true,
			'templates'        => $repos['templates']->list_templates( $type, $limit ),
			'snippets'         => $repos['snippets']->list_snippets( '', $limit, false ),
			'types'            => Niwa_AI_Template_Library_Types::labels(),
			'elementor_active' => did_action( 'elementor/loaded' ) || defined( 'ELEMENTOR_VERSION' ),
		);
	}

	private function preview_template_library_create_template( $args ) {
		$title = isset( $args['title'] ) ? sanitize_text_field( (string) $args['title'] ) : '';
		if ( '' === $title ) {
			return array( 'success' => false, 'error' => 'Naziv template-a je obavezan.' );
		}
		$type = Niwa_AI_Template_Library_Types::normalize_template_type( isset( $args['type'] ) ? $args['type'] : '' );
		return array(
			'success' => true,
			'action'  => array(
				'type'             => 'template_library_create_template',
				'label'            => 'Kreiraj Niwa template',
				'summary'          => 'Dodaje "' . $title . '" u Niwa Template Library kao ' . Niwa_AI_Template_Library_Types::label( $type ) . '.',
				'rollback_support' => 'manual',
				'args'             => array(
					'title'          => $title,
					'type'           => $type,
					'subtitle'       => isset( $args['subtitle'] ) ? sanitize_text_field( (string) $args['subtitle'] ) : '',
					'prompt'         => isset( $args['prompt'] ) ? wp_kses_post( (string) $args['prompt'] ) : '',
					'agent_prompt'   => isset( $args['agent_prompt'] ) ? sanitize_textarea_field( (string) $args['agent_prompt'] ) : '',
					'preview_prompt' => isset( $args['preview_prompt'] ) ? sanitize_textarea_field( (string) $args['preview_prompt'] ) : '',
					'preview_url'    => isset( $args['preview_url'] ) ? esc_url_raw( (string) $args['preview_url'] ) : '',
					'elementor_schema' => isset( $args['elementor_schema'] ) && is_array( $args['elementor_schema'] ) ? $args['elementor_schema'] : array(),
					'manifest'       => isset( $args['manifest'] ) && is_array( $args['manifest'] ) ? $args['manifest'] : array(),
				),
			),
		);
	}

	private function execute_template_library_create_template_action( $action ) {
		$repos  = $this->template_library_repositories();
		$args   = isset( $action['args'] ) && is_array( $action['args'] ) ? $action['args'] : array();
		$result = $repos['templates']->create_custom_template( $args );
		if ( is_wp_error( $result ) ) {
			return array( 'success' => false, 'error' => $result->get_error_message() );
		}
		return array(
			'success'          => true,
			'summary'          => 'Niwa template kreiran: ' . (string) $result['title'] . ' (ID ' . (string) $result['id'] . ').',
			'template'         => $result,
			'executed_actions' => array( array( 'type' => 'template_library_create_template', 'template_id' => $result['id'] ) ),
		);
	}

	private function preview_template_library_generate_snippet( $args ) {
		$template_id = isset( $args['template_id'] ) ? intval( $args['template_id'] ) : 0;
		if ( $template_id <= 0 ) {
			return array( 'success' => false, 'error' => 'template_id je obavezan.' );
		}
		return array(
			'success' => true,
			'action'  => array(
				'type'             => 'template_library_generate_snippet',
				'label'            => 'Generisi Niwa snippet',
				'summary'          => 'Generise lokalni snippet artefakt iz template-a #' . $template_id . '. Ako Elementor nije aktivan, koristi shortcode fallback.',
				'rollback_support' => 'manual',
				'args'             => array(
					'template_id'      => $template_id,
					'instructions'     => isset( $args['instructions'] ) ? sanitize_textarea_field( (string) $args['instructions'] ) : '',
					'title'            => isset( $args['title'] ) ? sanitize_text_field( (string) $args['title'] ) : '',
					'force_shortcode'  => ! empty( $args['force_shortcode'] ),
					'publish'          => ! empty( $args['publish'] ),
				),
			),
		);
	}

	private function execute_template_library_generate_snippet_action( $action ) {
		$repos = $this->template_library_repositories();
		$args  = isset( $action['args'] ) && is_array( $action['args'] ) ? $action['args'] : array();
		$template = $repos['templates']->get_template( isset( $args['template_id'] ) ? intval( $args['template_id'] ) : 0 );
		if ( ! $template ) {
			return array( 'success' => false, 'error' => 'Template nije pronadjen.' );
		}

		$force_shortcode = ! empty( $args['force_shortcode'] ) || ! ( did_action( 'elementor/loaded' ) || defined( 'ELEMENTOR_VERSION' ) );
		$type  = $this->template_library_snippet_type_for_template( $template, $force_shortcode );
		if ( Niwa_AI_Template_Library_Types::TYPE_ELEMENTOR_WIDGET === $type && ! $force_shortcode ) {
			return $this->execute_template_library_generate_elementor_widget_snippet( $repos, $template, $args );
		}

		$artifact = $repos['generator']->generate_artifact( $template, isset( $args['instructions'] ) ? (string) $args['instructions'] : '', $force_shortcode );
		$files    = isset( $artifact['files'] ) && is_array( $artifact['files'] ) ? $artifact['files'] : array();
		if ( $this->template_library_artifact_has_unresolved_template( $files ) ) {
			return array(
				'success' => false,
				'error'   => 'Niwa nije kreirala snippet jer LLM nije izgradio template, a nema konkretnih instrukcija za shortcode. Koristi template_library_insert_elementor za ciljnu Elementor stranicu ili posalji precizne instrukcije za shortcode fallback.',
				'artifact' => array(
					'llm_used'  => false,
					'llm_error' => isset( $artifact['llm_error'] ) ? (string) $artifact['llm_error'] : '',
				),
			);
		}
		$snippet = $repos['snippets']->create_snippet(
			array(
				'title'       => ! empty( $args['title'] ) ? $args['title'] : $template['title'],
				'description' => isset( $args['instructions'] ) ? $args['instructions'] : ( isset( $artifact['agent_notes'] ) ? (string) $artifact['agent_notes'] : '' ),
				'type'        => $type,
				'template_id' => intval( $template['id'] ),
				'files'       => $files,
			)
		);
		if ( is_wp_error( $snippet ) ) {
			return array( 'success' => false, 'error' => $snippet->get_error_message() );
		}

		$published = null;
		if ( ! empty( $args['publish'] ) ) {
			$valid = $repos['validator']->validate( $snippet );
			if ( is_wp_error( $valid ) ) {
				$repos['snippets']->mark_error( $snippet['id'], $valid->get_error_message() );
				return array( 'success' => false, 'error' => $valid->get_error_message(), 'snippet' => $snippet );
			}
			$written = $repos['filesystem']->write_snippet( $snippet, 'prod' );
			if ( is_wp_error( $written ) ) {
				$repos['snippets']->mark_error( $snippet['id'], $written->get_error_message() );
				return array( 'success' => false, 'error' => $written->get_error_message(), 'snippet' => $snippet );
			}
			$published = $repos['snippets']->mark_published( $snippet['id'] );
		}

		return array(
			'success'          => true,
			'summary'          => 'Snippet kreiran: ' . (string) $snippet['title'] . ' (ID ' . (string) $snippet['id'] . ', shortcode ' . (string) $snippet['shortcode'] . ').' . ( ! empty( $artifact['llm_used'] ) ? ' LLM je izgradio artefakt iz template prompta.' : ' Koriscen je lokalni fallback generator.' ),
			'snippet'          => $published ? $published : $snippet,
			'artifact'         => array(
				'llm_used'    => ! empty( $artifact['llm_used'] ),
				'llm_error'   => isset( $artifact['llm_error'] ) ? (string) $artifact['llm_error'] : '',
				'agent_notes' => isset( $artifact['agent_notes'] ) ? (string) $artifact['agent_notes'] : '',
			),
			'executed_actions' => array( array( 'type' => 'template_library_generate_snippet', 'snippet_id' => $snippet['id'] ) ),
		);
	}

	private function preview_template_library_insert_elementor( $args ) {
		$template_id = isset( $args['template_id'] ) ? intval( $args['template_id'] ) : 0;
		$post_id     = isset( $args['post_id'] ) ? intval( $args['post_id'] ) : 0;
		if ( $template_id <= 0 ) {
			return array( 'success' => false, 'error' => 'template_id je obavezan.' );
		}
		if ( $post_id <= 0 ) {
			return array( 'success' => false, 'error' => 'post_id je obavezan.' );
		}
		$post = get_post( $post_id );
		if ( ! $post ) {
			return array( 'success' => false, 'error' => 'Post nije pronadjen.' );
		}
		return array(
			'success' => true,
			'action'  => array(
				'type'             => 'template_library_insert_elementor',
				'label'            => 'Ubaci Niwa template u Elementor',
				'summary'          => 'Gradi Elementor elemente iz Niwa template-a #' . $template_id . ' i ubacuje ih na "' . (string) $post->post_title . '".',
				'rollback_plan'    => 'Vraca prethodni _elementor_data i post_content fallback kroz Elementor page-data backup.',
				'rollback_support' => 'full',
				'args'             => array(
					'template_id'  => $template_id,
					'post_id'      => $post_id,
					'instructions' => isset( $args['instructions'] ) ? sanitize_textarea_field( (string) $args['instructions'] ) : '',
					'position'     => isset( $args['position'] ) && 'before' === sanitize_key( (string) $args['position'] ) ? 'before' : 'after',
					'force_shortcode_fallback' => ! empty( $args['force_shortcode_fallback'] ),
				),
			),
		);
	}

	private function execute_template_library_insert_elementor_action( $action ) {
		$repos = $this->template_library_repositories();
		$args  = isset( $action['args'] ) && is_array( $action['args'] ) ? $action['args'] : array();
		$template_id = isset( $args['template_id'] ) ? intval( $args['template_id'] ) : 0;
		$post_id     = isset( $args['post_id'] ) ? intval( $args['post_id'] ) : 0;
		$template    = $repos['templates']->get_template( $template_id );
		if ( ! $template ) {
			return array( 'success' => false, 'error' => 'Template nije pronadjen.' );
		}
		if ( $post_id <= 0 || ! get_post( $post_id ) ) {
			return array( 'success' => false, 'error' => 'Elementor post nije pronadjen.' );
		}
		if ( ! method_exists( $this, 'get_elementor_data' ) || ! method_exists( $this, 'execute_elementor_update_page_data_action' ) ) {
			return array( 'success' => false, 'error' => 'Elementor write runtime nije ucitan.' );
		}

		$force_shortcode = ! empty( $args['force_shortcode_fallback'] ) || ! ( did_action( 'elementor/loaded' ) || defined( 'ELEMENTOR_VERSION' ) );
		$mode = isset( $template['output_mode'] ) ? sanitize_key( (string) $template['output_mode'] ) : 'shortcode';
		if ( 'admin_snippet' === $mode && ! $force_shortcode ) {
			return $this->execute_template_library_generate_snippet_action(
				array(
					'args' => array(
						'template_id'      => $template_id,
						'instructions'     => isset( $args['instructions'] ) ? (string) $args['instructions'] : '',
						'force_shortcode'  => false,
						'publish'          => true,
					),
				)
			);
		}
		if ( $force_shortcode ) {
			return $this->execute_template_library_generate_snippet_action(
				array(
					'args' => array(
						'template_id'      => $template_id,
						'instructions'     => isset( $args['instructions'] ) ? (string) $args['instructions'] : '',
						'force_shortcode'  => true,
						'publish'          => true,
					),
				)
			);
		}

		$current = $this->get_elementor_data( $post_id );
		if ( null === $current ) {
			return array( 'success' => false, 'error' => '_elementor_data je prazan ili neispravan za post ID ' . $post_id . '.' );
		}
		$current_raw = (string) get_post_meta( $post_id, '_elementor_data', true );
		$artifact = array( 'llm_used' => false, 'llm_error' => '', 'agent_notes' => '' );
		if ( in_array( $mode, array( 'elementor_widget', 'visual_app' ), true ) ) {
			$widget_result = $this->execute_template_library_generate_elementor_widget_snippet(
				$repos,
				$template,
				array(
					'instructions' => isset( $args['instructions'] ) ? (string) $args['instructions'] : '',
					'publish'      => true,
				)
			);
			if ( empty( $widget_result['success'] ) ) {
				return $widget_result;
			}
			$snippet_id = isset( $widget_result['snippet']['id'] ) ? intval( $widget_result['snippet']['id'] ) : 0;
			$settings_result = $repos['generator']->generate_elementor_widget_settings( $template, isset( $args['instructions'] ) ? (string) $args['instructions'] : '' );
			$settings   = isset( $settings_result['settings'] ) && is_array( $settings_result['settings'] ) ? $settings_result['settings'] : $repos['generator']->elementor_widget_settings_for_template( $template, isset( $args['instructions'] ) ? (string) $args['instructions'] : '' );
			$elements   = $repos['elementor_builder']->registered_widget_elements( 'niwa_tpl_' . $snippet_id, $settings );
			$artifact['llm_used']  = ! empty( $settings_result['llm_used'] );
			$artifact['llm_error'] = isset( $settings_result['error'] ) ? (string) $settings_result['error'] : '';
			$artifact['native_widget'] = array(
				'snippet_id'  => $snippet_id,
				'widget_type' => 'niwa_tpl_' . $snippet_id,
			);
		} else {
			$artifact = $repos['generator']->generate_artifact( $template, isset( $args['instructions'] ) ? (string) $args['instructions'] : '', false );
			$elements = isset( $artifact['elementor']['elements'] ) && is_array( $artifact['elementor']['elements'] ) ? $artifact['elementor']['elements'] : array();
		}
		$updated_data = $repos['elementor_builder']->append_to_page_data( $current, $elements, isset( $args['position'] ) ? (string) $args['position'] : 'after' );
		$post_content = isset( $artifact['elementor']['post_content'] ) ? (string) $artifact['elementor']['post_content'] : $repos['elementor_builder']->render_post_content( $updated_data );

		$result = $this->execute_elementor_update_page_data_action(
			array(
				'args' => array(
					'post_id'                 => $post_id,
					'elementor_data_json'     => wp_json_encode( $updated_data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ),
					'expected_current_sha256' => hash( 'sha256', $current_raw ),
					'post_content'            => $post_content,
					'has_post_content'        => true,
				),
			)
		);
		if ( empty( $result['success'] ) ) {
			return $result;
		}
		$result['summary'] = 'Niwa template "' . (string) $template['title'] . '" je izgradjen' . ( ! empty( $artifact['llm_used'] ) ? ' kroz LLM' : ' lokalnim fallback builderom' ) . ' i ubacen u Elementor post ' . $post_id . '.';
		$result['template'] = array(
			'id'    => $template_id,
			'title' => (string) $template['title'],
		);
		$result['artifact'] = array(
			'llm_used'    => ! empty( $artifact['llm_used'] ),
			'llm_error'   => isset( $artifact['llm_error'] ) ? (string) $artifact['llm_error'] : '',
			'agent_notes' => isset( $artifact['agent_notes'] ) ? (string) $artifact['agent_notes'] : '',
			'element_count' => count( $elements ),
		);
		if ( ! empty( $artifact['native_widget'] ) ) {
			$result['artifact']['native_widget'] = $artifact['native_widget'];
		}
		return $result;
	}

	private function preview_template_library_publish_snippet( $args ) {
		$snippet_id = isset( $args['snippet_id'] ) ? intval( $args['snippet_id'] ) : 0;
		if ( $snippet_id <= 0 ) {
			return array( 'success' => false, 'error' => 'snippet_id je obavezan.' );
		}
		return array(
			'success' => true,
			'action'  => array(
				'type'             => 'template_library_publish_snippet',
				'label'            => 'Publikuj Niwa snippet',
				'summary'          => 'Validira i publikuje snippet #' . $snippet_id . ' u wp-content/niwa-snippets/prod.',
				'rollback_support' => 'manual',
				'args'             => array( 'snippet_id' => $snippet_id ),
			),
		);
	}

	private function execute_template_library_publish_snippet_action( $action ) {
		$repos = $this->template_library_repositories();
		$args  = isset( $action['args'] ) && is_array( $action['args'] ) ? $action['args'] : array();
		$snippet = $repos['snippets']->get_snippet( isset( $args['snippet_id'] ) ? intval( $args['snippet_id'] ) : 0, true );
		if ( ! $snippet ) {
			return array( 'success' => false, 'error' => 'Snippet nije pronadjen.' );
		}
		$valid = $repos['validator']->validate( $snippet );
		if ( is_wp_error( $valid ) ) {
			$repos['snippets']->mark_error( $snippet['id'], $valid->get_error_message() );
			return array( 'success' => false, 'error' => $valid->get_error_message() );
		}
		$written = $repos['filesystem']->write_snippet( $snippet, 'prod' );
		if ( is_wp_error( $written ) ) {
			$repos['snippets']->mark_error( $snippet['id'], $written->get_error_message() );
			return array( 'success' => false, 'error' => $written->get_error_message() );
		}
		$live = $repos['snippets']->mark_published( $snippet['id'] );
		return array(
			'success'          => true,
			'summary'          => 'Snippet #' . (string) $snippet['id'] . ' je validiran i publikovan. Shortcode: ' . (string) $live['shortcode'],
			'snippet'          => $live,
			'path'             => isset( $written['path'] ) ? $written['path'] : '',
			'executed_actions' => array( array( 'type' => 'template_library_publish_snippet', 'snippet_id' => $snippet['id'] ) ),
		);
	}

	private function preview_template_library_generate_preview( $args ) {
		$template_id = isset( $args['template_id'] ) ? intval( $args['template_id'] ) : 0;
		if ( $template_id <= 0 ) {
			return array( 'success' => false, 'error' => 'template_id je obavezan.' );
		}
		$title = isset( $args['title'] ) && '' !== trim( (string) $args['title'] ) ? sanitize_text_field( (string) $args['title'] ) : 'Niwa template preview ' . $template_id;
		return array(
			'success' => true,
			'action'  => array(
				'type'             => 'template_library_generate_preview',
				'label'            => 'Generisi preview sliku',
				'summary'          => 'Generise Media Library preview sliku i vezuje je za template #' . $template_id . '.',
				'rollback_support' => 'full',
				'args'             => array(
					'template_id'           => $template_id,
					'prompt'                => isset( $args['prompt'] ) ? sanitize_textarea_field( (string) $args['prompt'] ) : '',
					'title'                 => $title,
					'alt_text'              => isset( $args['alt_text'] ) ? sanitize_text_field( (string) $args['alt_text'] ) : $title,
					'quality'               => isset( $args['quality'] ) ? sanitize_key( (string) $args['quality'] ) : 'medium',
					'size'                  => isset( $args['size'] ) ? sanitize_text_field( (string) $args['size'] ) : '1536x1024',
					'reference_image_urls'  => isset( $args['reference_image_urls'] ) && is_array( $args['reference_image_urls'] ) ? array_map( 'esc_url_raw', $args['reference_image_urls'] ) : array(),
					'force_regenerate'      => ! empty( $args['force_regenerate'] ),
				),
			),
		);
	}

	private function execute_template_library_generate_preview_action( $action ) {
		$args = isset( $action['args'] ) && is_array( $action['args'] ) ? $action['args'] : array();
		$template_id = isset( $args['template_id'] ) ? intval( $args['template_id'] ) : 0;
		$repos = $this->template_library_repositories();
		$template = $repos['templates']->get_template( $template_id );
		if ( ! $template ) {
			return array( 'success' => false, 'error' => 'Template nije pronadjen.' );
		}
		$prompt = trim( isset( $args['prompt'] ) ? (string) $args['prompt'] : '' );
		if ( '' === $prompt ) {
			$prompt = ! empty( $template['preview_prompt'] ) ? (string) $template['preview_prompt'] : (string) $template['prompt'];
		}

		$image_result = $this->execute_generate_image_action(
			array(
				'type' => 'generate_image',
				'args' => array(
					'prompt'               => $prompt,
					'title'                => isset( $args['title'] ) ? (string) $args['title'] : (string) $template['title'] . ' preview',
					'alt_text'             => isset( $args['alt_text'] ) ? (string) $args['alt_text'] : (string) $template['title'] . ' preview',
					'quality'              => isset( $args['quality'] ) ? (string) $args['quality'] : 'medium',
					'size'                 => isset( $args['size'] ) ? (string) $args['size'] : '1536x1024',
					'reference_image_urls' => isset( $args['reference_image_urls'] ) && is_array( $args['reference_image_urls'] ) ? $args['reference_image_urls'] : array(),
					'force_regenerate'     => ! empty( $args['force_regenerate'] ),
				),
			)
		);
		if ( empty( $image_result['success'] ) ) {
			return $image_result;
		}
		update_post_meta( $template_id, Niwa_AI_Template_Library_Types::META_PREVIEW_ID, intval( $image_result['attachment_id'] ) );
		update_post_meta( $template_id, Niwa_AI_Template_Library_Types::META_PREVIEW_URL, isset( $image_result['url'] ) ? esc_url_raw( $image_result['url'] ) : '' );

		$image_result['summary'] = 'Preview slika je generisana i vezana za template #' . $template_id . '.';
		$image_result['template'] = $repos['templates']->get_template( $template_id );
		return $image_result;
	}

	private function validate_template_library_action_args( $args ) {
		return array( 'success' => true );
	}

	private function template_library_snippet_type_for_template( $template, $force_shortcode = false ) {
		if ( $force_shortcode ) {
			return Niwa_AI_Template_Library_Types::TYPE_SHORTCODE;
		}
		$mode = isset( $template['output_mode'] ) ? sanitize_key( (string) $template['output_mode'] ) : 'shortcode';
		if ( 'admin_snippet' === $mode ) {
			return Niwa_AI_Template_Library_Types::TYPE_WORDPRESS_ADMIN_SNIPPET;
		}
		if ( 'elementor_widget' === $mode ) {
			return Niwa_AI_Template_Library_Types::TYPE_ELEMENTOR_WIDGET;
		}
		if ( 'visual_app' === $mode ) {
			return Niwa_AI_Template_Library_Types::TYPE_VISUAL_APP;
		}
		return Niwa_AI_Template_Library_Types::TYPE_SHORTCODE;
	}

	private function execute_template_library_generate_elementor_widget_snippet( $repos, $template, $args ) {
		$instructions = isset( $args['instructions'] ) ? (string) $args['instructions'] : '';
		$snippet = $repos['snippets']->create_snippet(
			array(
				'title'       => ! empty( $args['title'] ) ? $args['title'] : $template['title'],
				'description' => $instructions,
				'type'        => Niwa_AI_Template_Library_Types::TYPE_ELEMENTOR_WIDGET,
				'template_id' => intval( $template['id'] ),
				'files'       => array(),
			)
		);
		if ( is_wp_error( $snippet ) ) {
			return array( 'success' => false, 'error' => $snippet->get_error_message() );
		}

		$files = $repos['generator']->generate_elementor_widget_files( $template, $instructions, intval( $snippet['id'] ) );
		$snippet = $repos['snippets']->update_snippet_files( intval( $snippet['id'] ), $files );
		if ( is_wp_error( $snippet ) ) {
			return array( 'success' => false, 'error' => $snippet->get_error_message() );
		}

		$published = null;
		if ( ! empty( $args['publish'] ) ) {
			$valid = $repos['validator']->validate( $snippet );
			if ( is_wp_error( $valid ) ) {
				$repos['snippets']->mark_error( $snippet['id'], $valid->get_error_message() );
				return array( 'success' => false, 'error' => $valid->get_error_message(), 'snippet' => $snippet );
			}
			$written = $repos['filesystem']->write_snippet( $snippet, 'prod' );
			if ( is_wp_error( $written ) ) {
				$repos['snippets']->mark_error( $snippet['id'], $written->get_error_message() );
				return array( 'success' => false, 'error' => $written->get_error_message(), 'snippet' => $snippet );
			}
			$published = $repos['snippets']->mark_published( $snippet['id'] );
		}

		$live = $published ? $published : $snippet;
		return array(
			'success'          => true,
			'summary'          => 'Native Elementor widget kreiran: ' . (string) $live['title'] . ' (ID ' . (string) $live['id'] . ', widgetType niwa_tpl_' . (string) $live['id'] . ').',
			'snippet'          => $live,
			'artifact'         => array(
				'llm_used'    => false,
				'llm_error'   => '',
				'agent_notes' => 'Niwa generated a registered Elementor widget with native controls.',
			),
			'executed_actions' => array( array( 'type' => 'template_library_generate_snippet', 'snippet_id' => $live['id'] ) ),
		);
	}

	private function template_library_artifact_has_unresolved_template( $files ) {
		foreach ( is_array( $files ) ? $files : array() as $file ) {
			$name    = isset( $file['name'] ) ? strtolower( (string) $file['name'] ) : '';
			$content = isset( $file['content'] ) ? (string) $file['content'] : '';
			if ( 'template.html' === $name && ( false !== strpos( $content, 'data-niwa-template-unresolved="1"' ) || false !== strpos( $content, "data-niwa-template-unresolved='1'" ) ) ) {
				return true;
			}
		}
		return false;
	}
}
