<?php

/**
 * LolaCore - DistillDraftExtractor
 *
 * Pulls a playbook markdown file out of raw LLM output (preamble, fences, etc.).
 *
 * @package LolaCore
 * @license GPL-2.0-or-later
 */

declare(strict_types=1);

namespace LolaCore\Playbooks;

/**
 * Template-as-contract: the model must return frontmatter + body; this class recovers it when wrapped.
 */
final class DistillDraftExtractor
{
    /**
     * @return string|null Playbook markdown starting with --- or null when not recoverable.
     */
    public static function extract(string $raw): ?string
    {
        $text = trim($raw);
        if ($text === '') {
            return null;
        }

        $text = self::stripOuterCodeFence($text);

        if (preg_match('/\A---\r?\n[\s\S]+/u', $text) === 1) {
            return trim($text);
        }

        if (preg_match('/---\r?\n\s*name\s*:[\s\S]*/iu', $text, $matches) === 1) {
            return trim($matches[0]);
        }

        if (preg_match('/---\r?\n[\s\S]*?\r?\n---[\s\S]*/u', $text, $matches) === 1) {
            return trim($matches[0]);
        }

        return null;
    }

    private static function stripOuterCodeFence(string $text): string
    {
        if (preg_match('/\A```(?:markdown|md|yaml|yml)?\s*([\s\S]*?)\s*```\s*\z/i', $text, $matches) === 1) {
            return trim($matches[1]);
        }

        if (preg_match('/```(?:markdown|md|yaml|yml)?\s*([\s\S]*?)\s*```/i', $text, $matches) === 1) {
            $candidate = trim($matches[1]);
            if (str_starts_with($candidate, '---')) {
                return $candidate;
            }
        }

        return $text;
    }
}
