<?php
/**
 * Writes approved snippets to wp-content for inspection and runtime loading.
 *
 * @package Niwa_AI
 */

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

class Niwa_AI_Snippet_Filesystem {
	public function base_dir( $environment = 'prod' ) {
		$environment = 'dev' === sanitize_key( (string) $environment ) ? 'dev' : 'prod';
		return trailingslashit( WP_CONTENT_DIR ) . 'niwa-snippets/' . $environment;
	}

	public function snippet_dir( $snippet_id, $environment = 'prod' ) {
		return trailingslashit( $this->base_dir( $environment ) ) . 'snippet-' . intval( $snippet_id );
	}

	public function write_snippet( $snippet, $environment = 'prod' ) {
		$snippet_id = isset( $snippet['id'] ) ? intval( $snippet['id'] ) : 0;
		$files      = isset( $snippet['files'] ) && is_array( $snippet['files'] ) ? $snippet['files'] : array();
		if ( $snippet_id <= 0 ) {
			return new WP_Error( 'snippet_invalid_id', __( 'Invalid snippet ID.', 'niwa-ai' ) );
		}

		$dir = $this->snippet_dir( $snippet_id, $environment );
		if ( ! wp_mkdir_p( $dir ) ) {
			return new WP_Error( 'snippet_dir_failed', __( 'Could not create snippet directory.', 'niwa-ai' ) );
		}

		foreach ( $files as $file ) {
			$name = isset( $file['name'] ) ? sanitize_file_name( (string) $file['name'] ) : '';
			if ( '' === $name ) {
				continue;
			}
			$result = file_put_contents( trailingslashit( $dir ) . $name, isset( $file['content'] ) ? (string) $file['content'] : '' );
			if ( false === $result ) {
				return new WP_Error( 'snippet_write_failed', sprintf( __( 'Could not write snippet file: %s', 'niwa-ai' ), $name ) );
			}
		}

		return array(
			'success' => true,
			'path'    => $dir,
		);
	}
}
