from __future__ import annotations

import json

from app.core.agent.processes.v2.workflows.doc_update_from_feature_v2.subprocesses.common.rules_catalog import (
    RulesCatalog,
)
from app.core.agent.processes.v2.workflows.doc_update_from_feature_v2.subprocesses.common.template_models import (
    TemplateSpec,
)
from app.core.agent.processes.v2.workflows.doc_update_from_feature_v2.workflow_runtime.models import RequirementTaskContext
from app.core.agent.utils.llm import AgentLlmService


class GenerateFrontmatterStep:
    def __init__(self, llm: AgentLlmService) -> None:
        self._llm = llm

    def run(
        self,
        task: RequirementTaskContext,
        *,
        template: TemplateSpec,
        catalog: RulesCatalog,
        shared_context: dict[str, object],
    ) -> str:
        payload = {
            "task": {
                "section_key": task.section_key,
                "doc_type": task.doc_type,
                "id": task.doc_id,
                "application": task.application,
                "platform": task.platform,
                "domain": task.domain,
                "sub_domain": task.subdomain,
                "path": task.path,
                "heading": task.heading,
            },
            "requirement_text": task.body,
            "template": {"source_name": template.source_name, "template_text": template.template_text},
            "global_rules": catalog.global_text(),
            "frontmatter_rules": catalog.section_text("global/frontmatter.md"),
            "shared_context": shared_context,
        }
        return self._llm.generate(
            "v2_docs_update_v2.create_frontmatter",
            json.dumps(payload, ensure_ascii=False, indent=2),
            log_context="workflow.v2.docs_update.from_feature_v2.create.frontmatter",
        ).strip()
