<?php
namespace App\Helpers;

class PromptBuilder
{
    protected $input;

    public function __construct(array $input)
    {
        $this->input = $input;
    }

    public function systemMessage()
    {
        return "You are a professional Nigerian examination question setter trained in WAEC and NECO exam formatting standards. Follow the instructions strictly and output only the examination content without markdown or commentary.";
    }

    public function userMessage()
    {
        $i = $this->input;

        $topics = $this->normalizeTopics($i['topics'] ?? '');
        $subject = $i['subject'] ?? 'General Subject';
        $classLevel = $i['education_level'] ?? 'S.S.C.E';
        $objCount = $i['objective_count'] ?? 0;
        $theoryCount = $i['theory_count'] ?? 0;
        $difficulty = $i['difficulty'] ?? 'Mixed';
        $duration = $i['duration'] ?? '2 hours';
        $instructions = $i['instructions'] ?? 'Answer all questions.';

        $tpl = [];
        $tpl[] = "Generate the body of a Nigerian-style (WAEC/NECO) examination paper. The header (School Name and Session) will be added separately, so you must start directly with the Subject.";

        $tpl[] = "\nGenerate content with the following details:";
        $tpl[] = "- Subject: " . $subject;
        $tpl[] = "- Class Level: " . $classLevel;
        $tpl[] = "- Duration: " . $duration;
        $tpl[] = "- General Instructions: " . $instructions;
        $tpl[] = "- Difficulty: " . $difficulty;
        if ($topics) {
            $tpl[] = "- Topics: " . $topics;
        }

        if ($objCount > 0) {
            $tpl[] = "\nThe paper must contain a section titled 'SECTION A: OBJECTIVES' with $objCount multiple-choice questions.";
        }

        if ($theoryCount > 0) {
            $tpl[] = "It must also contain a section titled 'SECTION B: THEORY' with $theoryCount questions.";
        }

        $tpl[] = "\nFormatting Rules:";
        $tpl[] = "1. Start the entire output with the subject, duration, and instructions, formatted like a real exam paper.";
        $tpl[] = "2. Use capitalized text for section titles (e.g., 'SECTION A: OBJECTIVES'). Do not use markdown (like asterisks for bold).";
        $tpl[] = "3. For objective questions, provide four options labeled A, B, C, D.";
        $tpl[] = "4. After all questions, create a final section named 'ANSWERS' and list the correct option for each objective question (e.g., 1. B, 2. C).";
        $tpl[] = "5. Output only the examination content. Do not add any commentary.";

        return implode("\n", $tpl);
    }

    protected function normalizeTopics($raw)
    {
        $raw = trim($raw);
        if (empty($raw)) return '';
        // allow either comma separated or newline
        $parts = preg_split('/[,\n]+/', $raw);
        $parts = array_map('trim', $parts);
        $parts = array_filter($parts);
        return implode(', ', $parts);
    }
}
