<?php

namespace WPSN\Modules\ImportExport;

defined('ABSPATH') || exit;

/**
 * Converts an Import Assist export payload into flat CSV rows.
 */
final class ImportAssistCsvExporter
{
    /**
     * @return array<int,string>
     */
    public function headers(): array
    {
        return [
            'row_type',
            'assist_id',
            'exported_at_utc',
            'created_at',
            'kind',
            'source',
            'source_label',
            'context',
            'title',
            'review_url',
            'diff_compact',
            'diff_focus',
            'found',
            'applied',
            'skipped',
            'not_mapped',
            'warnings',
            'manual',
            'posts_updated',
            'terms_updated',
            'group',
            'group_label',
            'item_index',
            'item_text',
            'task_key',
            'task_label',
            'task_priority',
            'task_status',
            'task_url',
        ];
    }

    /**
     * @param array<string,mixed> $payload
     * @return array<int,array<int|string,string>>
     */
    public function rows(array $payload): array
    {
        $entry = isset($payload['entry']) && is_array($payload['entry']) ? $payload['entry'] : [];
        $summary = isset($entry['summary']) && is_array($entry['summary']) ? $entry['summary'] : [];
        $items = isset($entry['items']) && is_array($entry['items']) ? $entry['items'] : [];
        $diff = isset($payload['diff']) && is_array($payload['diff']) ? $payload['diff'] : [];
        $checklist = isset($payload['checklist']) && is_array($payload['checklist']) ? $payload['checklist'] : [];

        $base = [
            'assist_id' => (string) ($payload['assist_id'] ?? ''),
            'exported_at_utc' => (string) ($payload['exported_at_utc'] ?? ''),
            'created_at' => (string) ($entry['created_at'] ?? ''),
            'kind' => (string) ($entry['kind'] ?? ''),
            'source' => (string) ($entry['source'] ?? ''),
            'source_label' => (string) ($entry['source_label'] ?? ''),
            'context' => (string) ($entry['context'] ?? ''),
            'title' => (string) ($entry['title'] ?? ''),
            'review_url' => (string) ($payload['review_url'] ?? ''),
            'diff_compact' => (string) ($diff['compact'] ?? ''),
            'diff_focus' => (string) ($diff['focus'] ?? ''),
            'found' => (string) ((int) ($summary['found'] ?? 0)),
            'applied' => (string) ((int) ($summary['applied'] ?? 0)),
            'skipped' => (string) ((int) ($summary['skipped'] ?? 0)),
            'not_mapped' => (string) ((int) ($summary['not_mapped'] ?? 0)),
            'warnings' => (string) ((int) ($summary['warnings'] ?? 0)),
            'manual' => (string) ((int) ($summary['manual'] ?? 0)),
            'posts_updated' => (string) ((int) ($summary['posts_updated'] ?? 0)),
            'terms_updated' => (string) ((int) ($summary['terms_updated'] ?? 0)),
            'group' => '',
            'group_label' => '',
            'item_index' => '',
            'item_text' => '',
            'task_key' => '',
            'task_label' => '',
            'task_priority' => '',
            'task_status' => '',
            'task_url' => '',
        ];

        $rows = [];
        $rows[] = array_merge(['row_type' => 'summary'], $base);

        $groupLabels = [
            'source_found' => __('Found in source', 'wp-seo-next'),
            'applied' => __('Applied', 'wp-seo-next'),
            'skipped' => __('Skipped / source gaps', 'wp-seo-next'),
            'not_mapped' => __('Not mapped yet', 'wp-seo-next'),
            'warnings' => __('Warnings', 'wp-seo-next'),
            'manual_actions' => __('Manual follow-up', 'wp-seo-next'),
        ];

        foreach ($groupLabels as $group => $label) {
            $groupItems = $this->normalizeStringList($items[$group] ?? []);
            foreach ($groupItems as $index => $itemText) {
                $rows[] = array_merge(['row_type' => 'item'], $base, [
                    'group' => $group,
                    'group_label' => $label,
                    'item_index' => (string) ($index + 1),
                    'item_text' => $itemText,
                ]);
            }
        }

        foreach ($checklist as $task) {
            if (!is_array($task)) {
                continue;
            }
            $rows[] = array_merge(['row_type' => 'checklist'], $base, [
                'task_key' => (string) ($task['key'] ?? ''),
                'task_label' => (string) ($task['label'] ?? ''),
                'task_priority' => (string) ($task['priority'] ?? ''),
                'task_status' => !empty($task['checked']) ? 'checked' : 'open',
                'task_url' => (string) ($task['url'] ?? ''),
            ]);
        }

        return $rows;
    }

    /**
     * @param mixed $items
     * @return array<int,string>
     */
    private function normalizeStringList($items): array
    {
        if (!is_array($items)) {
            return [];
        }

        $out = [];
        foreach ($items as $item) {
            if (!is_scalar($item)) {
                continue;
            }
            $value = trim((string) $item);
            if ($value === '') {
                continue;
            }
            $out[] = $value;
        }

        return array_values(array_unique($out));
    }
}
