from __future__ import annotations

import re

from app.core.agent.processes.v2.workflows.doc_update_from_feature.workflow_runtime.context import DocUpdateFromFeatureContext
from app.core.agent.utils.workflow import WorkflowStep


class ResolveSourceStep(WorkflowStep[DocUpdateFromFeatureContext]):
    step_id = "resolve_source"
    title = "Определение источника аналитики"

    _PATH_PATTERN = re.compile(r"(/[^\n`]+?\.md)")
    _URL_PATTERN = re.compile(r"https?://[^\s)]+")

    async def run(self, context: DocUpdateFromFeatureContext) -> DocUpdateFromFeatureContext:
        if context.answer:
            return context
        query = context.route.user_query
        path = self._extract_path(query)
        if path:
            context.source_ref = path
            context.source_kind = "markdown_file"
            return context
        url = self._extract_url(query)
        if url:
            context.source_ref = url
            context.source_kind = "confluence_url" if "confluence" in url.lower() else "url"
            return context
        context.issues.append("Не удалось определить источник системной аналитики (ожидался путь .md или URL).")
        return context

    def trace_output(self, context: DocUpdateFromFeatureContext) -> dict[str, object]:
        return {"source_kind": context.source_kind, "source_ref": context.source_ref, "issues": len(context.issues)}

    def _extract_path(self, query: str) -> str:
        if "`" in query:
            for chunk in query.split("`"):
                value = chunk.strip().strip('"').strip("'")
                if value.endswith(".md") and value.startswith("/"):
                    return value
        match = self._PATH_PATTERN.search(query)
        if not match:
            return ""
        return match.group(1).strip().strip('"').strip("'")

    def _extract_url(self, query: str) -> str:
        match = self._URL_PATTERN.search(query)
        return match.group(0).strip() if match else ""
