from __future__ import annotations

import re
from typing import Any

from app.core.agent.processes.v2.workflows.doc_update_from_feature_v2.workflow_runtime.context import (
    DocUpdateFromFeatureV2Context,
)
from app.core.agent.utils.workflow import WorkflowStep


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

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

    async def run(self, context: DocUpdateFromFeatureV2Context) -> DocUpdateFromFeatureV2Context:
        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 _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)
        return match.group(1).strip().strip('"').strip("'") if match else ""

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

    def trace_input(self, context: DocUpdateFromFeatureV2Context) -> dict[str, Any]:
        query = str(context.route.user_query or "")
        return {"query_excerpt": query[:300], "query_len": len(query)}

    def trace_output(self, context: DocUpdateFromFeatureV2Context) -> dict[str, Any]:
        return {"source_kind": context.source_kind, "source_ref": context.source_ref}
