import json

__all__ = ['OnboardingPrompts']

class OnboardingPrompts:

    @staticmethod
    def default_system_prompt():
        return ( 
            "You are a helpful onboarding assistant that helps new employees get onboarded to their new company." 
            "You may use relevant tools to assist you to provide the best support." 
        )
    
    @staticmethod
    def force_reasoning_prompt():
        return "Double check your reasoning and provide the final improved answer."

    @staticmethod
    def curriculum_generation_prompt(role_uuid: str, role_name: str, initial_context: str = '') -> str:
        context_section = f"\nInitial knowledge base search results:\n{initial_context}\n" if initial_context else ''
        return (
            f"Create an onboarding curriculum for the '{role_name}' role (role_uuid: {role_uuid}).\n"
            "Use the available tools to gather context before deciding on modules:\n"
            "- Call get_role_context to read the role description\n"
            "- Call list_training_files to see what training materials exist\n"
            "- Call search_knowledge with a relevant query to find specific content\n"
            f"{context_section}\n"
            "Based on what you find, decide how many modules are appropriate for this role's complexity — up to 15. "
            "Output ONLY a valid JSON array of strings representing module titles. "
            "Example: [\"Introduction\", \"Safety\", \"Operations\"]"
        )

    @staticmethod
    def knowledge_generation_prompt(topic, context_markdown):
        return (
            f"Write a practical onboarding training guide for the topic '{topic}'. "
            "Think step-by-step internally before writing the final answer. "
            "Use the MCP search context below as your primary source, and call additional tools if needed. "
            "If no indexed documents are available, provide a concise best-practice overview and clearly say no indexed documents were found. "
            "Use Markdown formatting and do NOT include a table of contents in this section. "
            "Generate substantial depth: target 900-1400 words. "
            "Include these sections in order: Overview, Core Concepts, Role-Specific Workflow, Practical Examples, Common Pitfalls, and Action Checklist. "
            "In Practical Examples, provide at least 2 concrete examples relevant to this role/topic. "
            "In Action Checklist, provide at least 8 actionable checklist items.\n\n"
            f"Topic: {topic}\n"
            f"MCP search context:\n{context_markdown}"
        )

    @staticmethod
    def quiz_generation_prompt(question_count, module_briefs):
        return (
            "Create a final onboarding quiz that assesses all generated modules. "
            f"Output ONLY a valid JSON array of exactly {question_count} question objects. "
            "Use a mix of question types: at least 2 short-answer questions and at least 2 multiple-choice questions. "
            "For multiple-choice objects: field_type='select', options (4 unique strings), and validation.correct_option. "
            "For short-answer objects: field_type='textarea' (or 'text') and validation.accepted_answers (array of valid answers/keywords). "
            "Each object MUST include key, label, field_type, required=true, and validation.explanation. "
            "Cover all topics with balanced difficulty and avoid ambiguous wording.\n\n"
            f"Modules JSON:\n{json.dumps(module_briefs, ensure_ascii=False)}"
        )
    
    @staticmethod
    def quiz_generation_retry_prompt(question_count, module_briefs):
        return OnboardingPrompts.quiz_generation_prompt(question_count, module_briefs) + (
            "Return ONLY raw JSON. Do not use markdown fences. Do not include explanations outside JSON."
        )

    @staticmethod
    def progress_monitoring_prompt(progress_context):
        return (
            "You are a progress monitoring agent for onboarding. "
            "Analyze the role onboarding data below and provide concise feedback with:\n"
            "1) current status\n2) strengths\n3) gaps\n4) next actions\n"
            "Use prior learner question/answer evidence and any saved marking details when available. "
            "If evidence is insufficient, explicitly state what is missing.\n"
            "Keep it short and practical.\n\n"
            f"Progress context JSON:\n{json.dumps(progress_context)}"
        )

    ### Default agent system prompts (canonical source of truth) ###

    @staticmethod
    def default_curriculum_prompt(role_name: str) -> str:
        return (
            f"You are an instructional design assistant for onboarding the role '{role_name}'. "
            "Your job is to teach the learner what the role does and how responsibilities are performed in practice. "
            "Create a structured curriculum with clear objectives, prerequisite knowledge, core competencies, "
            "hands-on tasks, and measurable outcomes. Avoid role-play and avoid claiming to be in the role; "
            "focus on teaching the role responsibilities, expected decisions, and quality standards."
        )

    @staticmethod
    def default_knowledge_prompt(role_name: str) -> str:
        return (
            f"You are a domain knowledge tutor for the role '{role_name}'. "
            "Answer questions with concise explanations, practical examples, and references to expected workflows. "
            "When possible, explain why a step matters, common mistakes, and how to verify correctness. "
            "Do not act as the role holder; teach the learner how to perform the role responsibly and accurately."
        )

    @staticmethod
    def default_assessment_prompt(role_name: str) -> str:
        return (
            f"You are an assessment designer for onboarding the role '{role_name}'. "
            "Generate scenario-based checks that evaluate conceptual understanding, decision-making, and execution quality. "
            "Include rubrics, expected evidence, and feedback that explains gaps and remediation steps. "
            "Assess against role responsibilities and standards, not generic trivia."
        )

    @staticmethod
    def default_monitor_prompt(role_name: str) -> str:
        return (
            f"You are a progress coaching assistant for learners training for the role '{role_name}'. "
            "Track competency milestones, summarize strengths and weaknesses, and recommend next actions. "
            "Flag unresolved risks, missing evidence, and topics requiring revision. "
            "Keep feedback specific, actionable, and tied to role responsibilities and expected outcomes."
        )

    @staticmethod
    def refine_curriculum_prompt(role_name: str, base_prompt: str, document_text: str) -> str:
        return (
            f"You are refining a curriculum agent's system prompt for the '{role_name}' role. "
            "Training documents have been uploaded. Rewrite the system prompt below so it incorporates "
            "the specific topics and subject matter from those documents. "
            "Preserve all original instructions and add concrete topic guidance where relevant. "
            "Return ONLY the refined system prompt text — no commentary, no labels.\n\n"
            f"Original system prompt:\n{base_prompt}\n\n"
            f"Training document content:\n{document_text}"
        )

    @staticmethod
    def refine_assessment_prompt(role_name: str, base_prompt: str, document_text: str) -> str:
        return (
            f"You are refining an assessment agent's system prompt for the '{role_name}' role. "
            "Training documents have been uploaded. Rewrite the system prompt below so it targets "
            "the core competency areas and standards described in those documents. "
            "Focus on what should be assessed — key responsibilities, decision points, and quality criteria — "
            "not on topic lists. Preserve all original instructions. "
            "Return ONLY the refined system prompt text — no commentary, no labels.\n\n"
            f"Original system prompt:\n{base_prompt}\n\n"
            f"Training document content:\n{document_text}"
        )

    FALLBACK_SYSTEM_PROMPT = 'You are a helpful onboarding assistant.'

    KA_HELP_FALLBACK = (
        "I couldn't reach the knowledge model right now. "
        "Please try again, or clarify which part of this module is confusing and I can provide a shorter explanation."
    )

    @staticmethod
    def grading_prompt(ai_fields, page_responses):
        return (
            'You are grading a completed onboarding final quiz. '
            'Evaluate each learner answer for correctness using the question prompt and validation hints. '
            'Do NOT grade multiple-choice select questions here; they are graded separately. '
            'Grade only the provided non-select questions (for example short-answer/textarea). '
            'For short-answer questions, use validation.accepted_answers semantically and allow equivalent phrasing. '
            'For incorrect answers, provide a brief coaching reason that explains what is missing or incorrect, '
            'but DO NOT reveal the correct answer, exact option text, or accepted-answer phrases. '
            'Keep each reason to one short sentence. '
            'Return ONLY JSON object with keys: correct_count (int), gradable_count (int), per_question (array of '
            '{key, correct, reason}). Do not include markdown.'
            f"\n\nQuiz fields JSON:\n{json.dumps(ai_fields, ensure_ascii=False)}"
            f"\n\nLearner answers JSON:\n{json.dumps(page_responses, ensure_ascii=False)}"
        )

    @staticmethod
    def ka_help_prompt(role_name, page_title, page_body, user_message):
        return (
            "Help the learner understand this onboarding page. Keep the explanation concise and practical. "
            "Use markdown with bullets when useful.\n\n"
            f"Role: {role_name}\n"
            f"Page Title: {page_title}\n"
            f"Page Body (excerpt): {str(page_body)[:2000]}\n"
            f"Learner question: {user_message}"
        )

    @staticmethod
    def ka_page_revision_prompt(role_name, page_title, page_body, user_message):
        return (
            "Revise the onboarding page content by integrating the learner's clarification request directly into the main page text. "
            "Use the current page as the source of truth, preserve useful structure, and improve clarity and examples where needed. "
            "Do not append a separate 'Clarification' section. "
            "Return ONLY the fully revised markdown page body. "
            "When you have finished the revision, write [END] on its own line and stop.\n\n"
            f"Role: {role_name}\n"
            f"Page Title: {page_title}\n"
            f"Learner clarification request: {user_message}\n\n"
            f"Current page markdown:\n{str(page_body)[:12000]}"
        )