from pathlib import Path
from mixersystem.data.repository import get_context, rel_path
from mixersystem.data.agent_sdk import call_agent

_TEMPLATE_PATH = rel_path(str(Path(__file__).parent / "report-template.md"))
MODEL = "M"
_AGENT_NAME = "report_builder"

PROMPT = """\
{role}

<quick-start>
1. Read the existing artifacts for this job:
{artifacts}
2. Read the following project docs:
{docs}
3. Read the rules for writing reports:
{rules}
4. Read the specific instructions (if any):
{instructions}
5. Read the report template at """ + _TEMPLATE_PATH + """
6. Be ready to write the report.
</quick-start>
{questions_section}

<steps>
1. Read the session artifacts — task.md, plan.md, work.md, update.md, upgrade.md — whichever exist
2. Synthesize a concise report that captures ALL changes made in this session
3. Write the report to {report_path}, following the template structure
</steps>

<constraints>
- The report subject line must be under 72 characters
- Use conventional commit format: `type(scope): description`
- Common types: feat, fix, refactor, docs, chore, test, style, perf
- The body should be a concise bullet list of what changed — no filler
- Only describe changes that actually happened based on the artifacts — do not invent changes
- Follow the report template structure exactly
- You MUST follow the exact output format below
</constraints>

<output-format>
[RESULT]
status: DONE
[NOTES]
Summary of the report written.
</output-format>"""


async def run(*, instructions: str | None = None, **kwargs) -> str:
    """Synthesize a report from session artifacts. Returns session_id."""
    ctx = get_context()
    model = MODEL

    report_path = ctx.paths["report_path"]

    role_lines = ["You are the Report Builder. You must read all provided inputs."]

    work_path = ctx.paths["work_path"]
    update_path = ctx.paths["update_path"]
    upgrade_path = ctx.paths["upgrade_path"]

    if Path(work_path).is_file():
        role_lines.append("Base your report primarily on the work report.")
    if Path(update_path).is_file():
        role_lines.append("Include documentation changes from the update report.")
    if Path(upgrade_path).is_file():
        role_lines.append("Include rule improvements from the upgrade report.")
    if Path(report_path).is_file():
        role_lines.append(f"A previous version of {rel_path(report_path)} exists. Revise it based on the new inputs — do not start from scratch.")
    if instructions:
        role_lines.append("Follow the additional instructions provided.")
    role_lines.append("The instructions always take priority over other inputs.")
    role = "<role>\n" + "\n".join(role_lines) + "\n</role>"

    questions_context = ctx.resolve_questions("report")
    questions_section = ""
    if questions_context:
        questions_section = (
            "<answered-questions>\n"
            "The following questions have been answered. You MUST implement these answers in your output.\n"
            f"{questions_context}"
            "</answered-questions>"
        )

    extra_prompt = PROMPT.format(
        role=role,
        artifacts=ctx.resolve_artifacts(),
        docs=ctx.resolve_docs(),
        rules=ctx.resolve_rules(_AGENT_NAME.split("_", 1)[0]),
        instructions=instructions or "",
        report_path=rel_path(report_path),
        questions_section=questions_section,
    )

    _, session_id = await call_agent(
        prompt=extra_prompt,
        model=model,
        agent_name=_AGENT_NAME,
        **kwargs,
    )
    return session_id
