<?php

namespace GriffinForms\Includes\Ai\PromptRegistry\Handlers\Row;

class RowCopyResolver
{
    public function resolveHeading(array $row, array $structure): string
    {
        return $this->resolveHeadingFromFields($row, $structure, true);
    }

    public function resolveDescription(array $row, string $prompt = ''): string
    {
        return $this->resolveDescriptionValue($row, $prompt);
    }

    public function resolveHeadingAlternative(array $row, array $structure, string $current_value): string
    {
        $alternatives = [
            __('Section Details', 'griffinforms-form-builder'),
            __('Your Details', 'griffinforms-form-builder'),
            __('Profile Details', 'griffinforms-form-builder'),
            __('More Information', 'griffinforms-form-builder'),
        ];

        foreach ($alternatives as $candidate) {
            if (strcasecmp($candidate, $current_value) !== 0) {
                return $candidate;
            }
        }

        return __('Section', 'griffinforms-form-builder');
    }

    public function resolveDescriptionAlternative(array $row, string $prompt, string $current_value): string
    {
        $alternatives = [
            __('Tell us a little about how we can reach you.', 'griffinforms-form-builder'),
            __('Share the information requested below.', 'griffinforms-form-builder'),
            __('Provide any extra details that help us understand your request.', 'griffinforms-form-builder'),
            __('Provide the requested information.', 'griffinforms-form-builder'),
        ];

        foreach ($alternatives as $candidate) {
            if (strcasecmp($candidate, $current_value) !== 0) {
                return $candidate;
            }
        }

        return __('Provide the requested information.', 'griffinforms-form-builder');
    }

    public function resolveHeadingFromFields(array $row, array $structure, bool $force_rewrite = false): string
    {
        $existing = $this->normalizeText((string) ($row['heading'] ?? ''), 120);
        if (!$force_rewrite && $existing !== '' && !in_array(strtolower($existing), ['row', 'section'], true)) {
            return $existing;
        }

        $field_labels = [];
        foreach ((array) ($row['columns'] ?? []) as $column) {
            foreach ((array) ($column['fields'] ?? []) as $field) {
                $label = $this->normalizeText((string) ($field['label'] ?? ''), 60);
                if ($label !== '') {
                    $field_labels[] = $label;
                }
            }
        }

        $field_blob = strtolower(implode(' ', array_slice($field_labels, 0, 4)));
        $candidates = [];

        if (preg_match('/\b(name|email|phone|contact|address)\b/', $field_blob)) {
            $candidates[] = __('Contact Details', 'griffinforms-form-builder');
            $candidates[] = __('Your Details', 'griffinforms-form-builder');
        } elseif (preg_match('/\b(billing|invoice|payment|card|price|amount)\b/', $field_blob)) {
            $candidates[] = __('Billing Details', 'griffinforms-form-builder');
            $candidates[] = __('Payment Details', 'griffinforms-form-builder');
        } elseif (preg_match('/\b(company|business|organization|job|title|role)\b/', $field_blob)) {
            $candidates[] = __('Business Details', 'griffinforms-form-builder');
            $candidates[] = __('Profile Details', 'griffinforms-form-builder');
        } elseif (preg_match('/\b(message|comment|notes|details|description|about)\b/', $field_blob)) {
            $candidates[] = __('Additional Details', 'griffinforms-form-builder');
            $candidates[] = __('More Information', 'griffinforms-form-builder');
        } elseif (!empty($field_labels)) {
            $candidates[] = __('Form Details', 'griffinforms-form-builder');
            $candidates[] = __('Section Details', 'griffinforms-form-builder');
        }

        foreach ($candidates as $candidate) {
            if (strcasecmp($candidate, $existing) !== 0) {
                return $candidate;
            }
        }

        return $this->resolveHeadingAlternative($row, $structure, $existing);
    }

    public function resolveDescriptionValue(array $row, string $prompt = ''): string
    {
        $prompt = strtolower(trim($prompt));
        $current = $this->normalizeText((string) ($row['description'] ?? ''), 180);

        $line_count = 1;
        if (preg_match('/\b(\d+)\s*(?:line|lines)\b/', $prompt, $matches)) {
            $line_count = max(1, min(4, (int) $matches[1]));
        } elseif (preg_match('/\b(two|three|four)\s*(?:line|lines)\b/', $prompt, $matches)) {
            $line_count = ['two' => 2, 'three' => 3, 'four' => 4][$matches[1]] ?? 1;
        }

        $field_labels = [];
        foreach ((array) ($row['columns'] ?? []) as $column) {
            foreach ((array) ($column['fields'] ?? []) as $field) {
                $label = $this->normalizeText((string) ($field['label'] ?? ''), 60);
                if ($label !== '') {
                    $field_labels[] = $label;
                }
            }
        }

        $field_blob = strtolower(implode(' ', array_slice($field_labels, 0, 4)));
        if (preg_match('/\b(name|email|phone|contact|address)\b/', $field_blob)) {
            $line1 = __('Tell us how we can reach you.', 'griffinforms-form-builder');
            $line2 = __('Include the best contact details for this section.', 'griffinforms-form-builder');
        } elseif (preg_match('/\b(billing|invoice|payment|card|price|amount)\b/', $field_blob)) {
            $line1 = __('Share the billing or payment details requested here.', 'griffinforms-form-builder');
            $line2 = __('Include any information needed to complete this section.', 'griffinforms-form-builder');
        } elseif (preg_match('/\b(company|business|organization|job|title|role)\b/', $field_blob)) {
            $line1 = __('Tell us a little about your business or role.', 'griffinforms-form-builder');
            $line2 = __('Include the details that best describe this section.', 'griffinforms-form-builder');
        } else {
            $line1 = __('Provide the information requested in this section.', 'griffinforms-form-builder');
            $line2 = __('Add any extra details that apply.', 'griffinforms-form-builder');
        }

        $parts = [trim($line1)];
        if ($line_count >= 2) {
            $parts[] = trim($line2);
        }
        if ($line_count >= 3) {
            $parts[] = __('Add any extra context needed to complete this section.', 'griffinforms-form-builder');
        }
        if ($line_count >= 4) {
            $parts[] = __('Keep your response clear and specific.', 'griffinforms-form-builder');
        }

        $value = trim(implode(' ', array_filter($parts)));
        return $value !== '' ? $value : $current;
    }

    protected function normalizeText(string $value, int $limit): string
    {
        $value = trim(wp_strip_all_tags($value));
        if ($value === '') {
            return '';
        }

        if (function_exists('mb_substr')) {
            return mb_substr($value, 0, $limit);
        }

        return substr($value, 0, $limit);
    }
}
