# -*- coding: utf-8 -*-
"""
Agile Together — the prompts each step hands the student, in ENGLISH.

WHY A PARALLEL MODULE AND NOT T()
    A prompt is not a sentence: it is a structured document of 5 to 8 blocks that
    ends by naming, one per line, the EXACT headings the answer must carry. Put
    that through the phrase catalogue and it becomes 60 fragments nobody can review
    side by side. Here the whole prompt lives in one place, in one language, and
    the two versions can be read against each other.

THE HEADINGS ARE A CONTRACT, NOT PROSE
    Every heading below has an alias in `_together_kit/vocabulario.py` pointing at
    the canonical Portuguese label the steps still look for:

        PRODUCT GOAL -> META DO PRODUTO      STORIES   -> HISTORIAS
        SELECTED     -> SELECIONADOS         SPRINT GOAL -> META DA SPRINT
        REFINEMENT   -> REFINAMENTO          TASKS     -> TAREFAS
        FOCUS TODAY  -> FOCO DE HOJE         NEW TASKS -> NOVAS TAREFAS
        IMPEDIMENT   -> IMPEDIMENTO          RENAME/ADD -> RENOMEAR/ADICIONAR
        WHAT WENT WELL -> DEU CERTO          PROBLEMS  -> PROBLEMAS

    And the item fields go the same way: `priority:` -> prioridade,
    `points:` -> pontos, `acceptance:` -> criterio de aceitacao, `new:` -> novo,
    `detail:` -> detalhe.

    ⛔ CHANGE A HEADING HERE AND YOU MUST ADD ITS ALIAS THERE. Otherwise the AI
    answers perfectly, the parser finds nothing, the card comes back empty and the
    student thinks it is their fault. That failure is silent — it never raises.
"""

_CABECALHO = (
    "You are helping me on a real project run with Scrum and OKR "
    "(the Agile Together method). You do NOT execute code and you do NOT read my "
    "files: answer in TEXT, which I will take to my board."
)

_FORMATO = (
    "ANSWER FORMAT (required)\n"
    "- Write the headings in CAPITALS, each on its own line, exactly as asked.\n"
    "- Every item starts with \"• \" and the fields come after \"|\", like this:\n"
    "    • Item title | priority: High | points: 3\n"
    "- No markdown (**, ##, tables), no code, no commentary outside the blocks."
)


def _montar(*blocos):
    return "\n\n".join(b.strip() for b in blocos if b and b.strip())


# ─────────────────────────────────────────────────────────────────────────────
# Step: Product Goal + Product Backlog
# ─────────────────────────────────────────────────────────────────────────────
def backlog(objetivo, total_sprints, quantos=9, software=False):
    dominio = (
        "This project IS a software development project: the items are "
        "deliverable features, with value visible to whoever uses them."
        if software else
        "This project is NOT software: the items are PRACTICAL MACRO-ACTIVITIES "
        "that I will actually carry out (habits, commitments, day-to-day "
        "deliverables). Use action verbs in the infinitive (Run, Prepare, Record). "
        "Do NOT use the \"As an X, I want Y\" format — that one is for software."
    )
    return _montar(
        _CABECALHO,
        f"MY OBJECTIVE (OKR): {objetivo}",
        dominio,
        f"I need two things:\n"
        f"1. The PRODUCT GOAL: one inspiring, concrete and verifiable sentence, "
        f"reachable in {total_sprints} Sprints. It is the commitment for the Product "
        f"Backlog (Scrum Guide): the backlog is ordered against it.\n"
        f"2. The PRODUCT BACKLOG: {quantos} items ordered by priority, with story "
        f"points (scale 1, 2, 3, 5, 8). Spread them across High (the main levers of "
        f"the objective), Medium (consistency) and Low (fine tuning).",
        _FORMATO,
        "Answer with these two headings:\n"
        "PRODUCT GOAL: <the sentence>\n"
        "STORIES:\n"
        "• <item> | priority: High | points: 3",
    )


def atualizar_backlog(objetivo, titulos):
    lista = "\n".join(f"  - {t}" for t in titulos) or "  (the backlog is empty)"
    return _montar(
        _CABECALHO,
        f"MY OBJECTIVE (OKR): {objetivo}",
        f"This is my Product Backlog TODAY, title by title:\n{lista}",
        "Review this backlog against the objective. You may (a) rewrite titles that "
        "are vague or that do not help the objective and (b) propose items that are "
        "missing. When you rewrite one, repeat a FRAGMENT of the current title so I "
        "know which one it is.",
        _FORMATO,
        "Answer with these two headings (either one may come back empty):\n"
        "RENAME:\n"
        "• <fragment of the current title> | new: <new title> | priority: High | points: 2\n"
        "ADD:\n"
        "• <new title> | priority: Medium | points: 3",
    )


def refinar_backlog(objetivo, titulos):
    lista = "\n".join(f"  - {t}" for t in titulos) or "  (the backlog is empty)"
    return _montar(
        _CABECALHO,
        f"MY OBJECTIVE (OKR): {objetivo}",
        f"My Product Backlog:\n{lista}",
        "Refine each item: confirm priority and points and write verifiable "
        "ACCEPTANCE CRITERIA (in the form \"Given ... When ... Then ...\"). "
        "Acceptance criteria are what let me say 'this is done' without an argument.",
        _FORMATO,
        "Answer with this heading:\n"
        "REFINEMENT:\n"
        "• <fragment of the current title> | priority: High | points: 3 | "
        "acceptance: Given X, When Y, Then Z; Given A, When B, Then C",
    )


# ─────────────────────────────────────────────────────────────────────────────
# Step: break an item down into tasks
# ─────────────────────────────────────────────────────────────────────────────
def tarefas(titulo_do_item, descricao=""):
    ctx = f"\nItem description: {descricao}" if descricao else ""
    return _montar(
        _CABECALHO,
        f"I want to break this item of my Sprint Backlog down into tasks:\n"
        f"  {titulo_do_item}{ctx}",
        "Between 3 and 7 tasks, each one fitting in ONE DAY or less, with a verb in "
        "the infinitive. Cover what usually gets forgotten too (preparation, "
        "verification, the case that goes wrong).",
        _FORMATO,
        "Answer with this heading:\nTASKS:\n• <task>",
    )


# ─────────────────────────────────────────────────────────────────────────────
# Step: Sprint Planning
# ─────────────────────────────────────────────────────────────────────────────
def planning(sprint, meta_produto, titulos, pontos_sugeridos=None):
    lista = "\n".join(f"  - {t}" for t in titulos) or "  (the Product Backlog is empty)"
    capacidade = (f"\nLast Sprint I completed about {pontos_sugeridos} points — "
                  f"use that as capacity." if pontos_sugeridos else "")
    return _montar(
        _CABECALHO,
        f"Let us plan SPRINT {sprint}." +
        (f"\nPRODUCT GOAL: {meta_produto}" if meta_produto else ""),
        f"These are the items that EXIST in my Product Backlog — use ONLY these "
        f"titles, copied exactly as they are:\n{lista}{capacidade}",
        "Choose the items that fit in this Sprint and write the SPRINT GOAL: a "
        "single sentence stating the value the Sprint delivers (the commitment for "
        "the Sprint Backlog, per the Scrum Guide). The goal is not the list of items "
        "— it is the why behind them. Do not invent an item that is not in the list "
        "above.",
        _FORMATO,
        "Answer with these two headings:\n"
        "SPRINT GOAL: <the sentence>\n"
        "SELECTED:\n• <title copied from the list above>",
    )


# ─────────────────────────────────────────────────────────────────────────────
# Step: Daily Scrum
# ─────────────────────────────────────────────────────────────────────────────
def daily(sprint, meta_sprint, no_sprint_backlog, concluidos):
    def _bloco(titulo, itens):
        corpo = "\n".join(f"  - {t}" for t in itens) or "  (none)"
        return f"{titulo}\n{corpo}"
    return _montar(
        _CABECALHO,
        f"DAILY SCRUM of Sprint {sprint}." +
        (f"\nSPRINT GOAL: {meta_sprint}" if meta_sprint else ""),
        _bloco("In progress in the Sprint Backlog:", no_sprint_backlog),
        _bloco("Already completed in this Sprint:", concluidos),
        "The Daily inspects progress toward the SPRINT GOAL and replans the day. "
        "Tell me what I should focus on TODAY — choosing among the items in progress "
        "— and, if it helps, propose short new tasks for today. If something is "
        "blocking the goal, write it in the IMPEDIMENT block.",
        _FORMATO,
        "Answer with these headings (IMPEDIMENT may come back empty):\n"
        "FOCUS TODAY:\n• <title copied from the in-progress list>\n"
        "NEW TASKS:\n• <short title> | detail: <one line>\n"
        "  (the course marks these with [AI] on the board — that is what KR4 measures)\n"
        "IMPEDIMENT: <one line, or 'none'>",
    )


# ─────────────────────────────────────────────────────────────────────────────
# Step: Sprint Review
# ─────────────────────────────────────────────────────────────────────────────
def review(sprint, meta_sprint, entregues, pendentes):
    def _bloco(titulo, itens):
        corpo = "\n".join(f"  - {t}" for t in itens) or "  (none)"
        return f"{titulo}\n{corpo}"
    return _montar(
        _CABECALHO,
        f"SPRINT REVIEW of Sprint {sprint}." +
        (f"\nSPRINT GOAL: {meta_sprint}" if meta_sprint else ""),
        _bloco("Delivered (completed):", entregues),
        _bloco("Not completed:", pendentes),
        "The Sprint Review inspects the INCREMENT with the stakeholders and adapts "
        "the Product Backlog — it is not a status presentation. Write an executive "
        "summary of 3 to 5 lines (what actually changed for whoever uses the result, "
        "and what was left out and why) and, if there is any, the feedback I should "
        "take to the Product Backlog.",
        _FORMATO,
        "Answer with these two headings:\n"
        "SUMMARY: <3 to 5 lines>\n"
        "FEEDBACK: <1 to 3 lines, or 'none'>",
    )


# ─────────────────────────────────────────────────────────────────────────────
# Step: Sprint Retrospective
# ─────────────────────────────────────────────────────────────────────────────
def retro(sprint, krs_texto=""):
    return _montar(
        _CABECALHO,
        f"SPRINT RETROSPECTIVE of Sprint {sprint}.",
        (f"My indicators in this Sprint:\n{krs_texto}" if krs_texto else ""),
        "The Retrospective looks at the PROCESS (people, interactions, tools, "
        "Definition of Done), not at the product. Help me close the Sprint "
        "honestly: what worked, what got in the way and — the part that counts — at "
        "most 3 concrete actions for the next Sprint. A vague action (\"improve "
        "communication\") is no use: each one has to fit on a card.",
        _FORMATO,
        "Answer with these three headings:\n"
        "WHAT WENT WELL:\n• <item>\n"
        "PROBLEMS:\n• <item>\n"
        "ACTIONS:\n• <concrete action for the next Sprint>",
    )


# ─────────────────────────────────────────────────────────────────────────────
# Step: KR check-in and closing
# ─────────────────────────────────────────────────────────────────────────────
def checkin(objetivo, relatorio_krs):
    return _montar(
        _CABECALHO,
        f"MY OBJECTIVE (OKR): {objetivo}",
        f"This is the report of my 4 Key Results, read from my board:\n\n{relatorio_krs}",
        "Do the weekly check-in with me: for each KR, state the confidence of "
        "reaching the target (green >=70%, amber 40-69%, red <40%) and why. Then "
        "choose 1 to 3 concrete actions for the week — not ten. Where the number "
        "does not support a conclusion, say that it does not.",
        _FORMATO,
        "Answer with these two headings:\n"
        "READING:\n• KR1 | confidence: green | why: <one line>\n"
        "ACTIONS:\n• <action for this week>",
    )


def encerramento(objetivo, dados):
    return _montar(
        _CABECALHO,
        f"MY OBJECTIVE (OKR): {objetivo}",
        f"This is the data from my board at the end of the Sprints:\n\n{dados}",
        "Help me close the cycle: the achievement of each KR (with the number), the "
        "patterns that show up across the three Sprints and the 3 lessons worth "
        "taking to the next project. The final curation is mine — do not invent a "
        "number that is not in the data above.",
        _FORMATO,
        "Answer with these three headings:\n"
        "ACHIEVEMENT:\n• KR1 | result: <number> | reading: <one line>\n"
        "PATTERNS:\n• <observed pattern>\n"
        "LESSONS:\n• <lesson learned>",
    )
