<?php

declare(strict_types=1);

/**
 * @return list<string>|null
 */
function fate_store_hours_weekday_lines_from_opening_raw(?string $placeOpeningHoursRaw): ?array
{
    $raw = $placeOpeningHoursRaw !== null ? trim(strip_tags((string) $placeOpeningHoursRaw)) : '';
    if ($raw === '') {
        return null;
    }
    try {
        $od = json_decode($raw, true, 12, JSON_THROW_ON_ERROR);
    } catch (Throwable) {
        return null;
    }
    if (!is_array($od) || empty($od['weekday_text']) || !is_array($od['weekday_text'])) {
        return null;
    }
    $lines = [];
    foreach ($od['weekday_text'] as $line) {
        $lines[] = trim((string) $line);
    }

    return array_values(array_filter($lines, static fn (string $s): bool => $s !== ''));
}

/**
 * 將 business_hours_json（store_public API）、legacy 起迄與 place_opening_hours 後備資料整理為版面用區塊。
 *
 * @return array{
 *   today:?string,
 *   rows:list<array{label:string,value:string}>,
 *   legacy:?string,
 *   raw_lines:list<string>
 * }
 */
function fate_store_hours_blocks(?string $businessHoursJson, string $bhStart, string $bhEnd, ?string $placeOpeningHoursRaw): array
{
    $out = [
        'today' => null,
        'rows' => [],
        'legacy' => null,
        'raw_lines' => [],
    ];

    $decodedBh = null;
    if ($businessHoursJson !== null && trim($businessHoursJson) !== '') {
        try {
            $decodedBh = json_decode($businessHoursJson, true, 12, JSON_THROW_ON_ERROR);
        } catch (Throwable) {
            $decodedBh = null;
        }
    }

    if (is_array($decodedBh)) {
        if (!empty($decodedBh['today_line'])) {
            $t = trim((string) $decodedBh['today_line']);
            if ($t !== '') {
                $out['today'] = $t;
            }
        }
        if (!empty($decodedBh['weekday_lines']) && is_array($decodedBh['weekday_lines'])) {
            foreach ($decodedBh['weekday_lines'] as $line) {
                $line = trim((string) $line);
                if ($line === '') {
                    continue;
                }
                if (preg_match('/^(.+?)[:：]\s*(.+)$/u', $line, $m) === 1) {
                    $out['rows'][] = ['label' => trim($m[1]), 'value' => trim($m[2])];
                } else {
                    $out['rows'][] = ['label' => '', 'value' => $line];
                }
            }
        }
        if (!empty($decodedBh['legacy_range'])) {
            $lr = trim((string) $decodedBh['legacy_range']);
            if ($lr !== '') {
                $out['legacy'] = $lr;
            }
        }
    }

    if ($out['rows'] === []) {
        $wk = fate_store_hours_weekday_lines_from_opening_raw($placeOpeningHoursRaw);
        if ($wk !== null) {
            $todayIndex = (int) date('N') - 1;
            foreach ($wk as $idx => $line) {
                if ($idx === $todayIndex && $out['today'] === null) {
                    $out['today'] = $line;
                }
                if (preg_match('/^(.+?)[:：]\s*(.+)$/u', $line, $m) === 1) {
                    $out['rows'][] = ['label' => trim($m[1]), 'value' => trim($m[2])];
                } else {
                    $out['rows'][] = ['label' => '', 'value' => $line];
                }
            }
        }
    }

    if ($out['legacy'] === null && ($bhStart !== '' || $bhEnd !== '')) {
        $out['legacy'] = trim($bhStart . ($bhStart !== '' && $bhEnd !== '' ? ' — ' : '') . $bhEnd);
    }

    if ($out['rows'] === [] && $out['today'] === null && ($out['legacy'] === null || $out['legacy'] === '')) {
        $rawClean = $placeOpeningHoursRaw !== null ? trim(strip_tags((string) $placeOpeningHoursRaw)) : '';
        if ($rawClean !== '' && fate_store_hours_weekday_lines_from_opening_raw($placeOpeningHoursRaw) === null) {
            $lines = preg_split('/\R+/u', $rawClean) ?: [];
            foreach ($lines as $line) {
                $line = trim((string) $line);
                if ($line !== '') {
                    $out['raw_lines'][] = $line;
                }
            }
        }
    }

    return $out;
}

function fate_store_hours_has_content(array $blocks): bool
{
    return $blocks['today'] !== null
        || $blocks['rows'] !== []
        || ($blocks['legacy'] !== null && $blocks['legacy'] !== '')
        || $blocks['raw_lines'] !== [];
}
