# #region AssistantCommandParser [C:4] [TYPE Module] [SEMANTICS assistant, command, parser, nlu, intent]
# @BRIEF Deterministic RU/EN command text parser that converts user messages into intent payloads.
# @LAYER API
# @RELATION DEPENDS_ON -> [AssistantResolvers]
# @INVARIANT  Every return path includes domain, operation, entities, confidence, risk_level, requires_confirmation.

from __future__ import annotations

import re
from typing import Any

from src.core.config_manager import ConfigManager
from src.core.logger import belief_scope, logger

from ._resolvers import _extract_id, _is_production_env


# #region _parse_command [C:4] [TYPE Function]
# @BRIEF Deterministically parse RU/EN command text into intent payload.
# @DATA_CONTRACT  Input[message:str, config_manager:ConfigManager] -> Output[Dict[str,Any]{domain,operation,entities,confidence,risk_level,requires_confirmation}]
# @RELATION DEPENDS_ON -> [_extract_id]
# @RELATION DEPENDS_ON -> [_is_production_env]
# @SIDE_EFFECT  None (pure parsing logic).
# @PRE  message contains raw user text and config manager resolves environments.
# @POST  Returns intent dict with domain/operation/entities/confidence/risk fields.
# @INVARIANT  every return path includes domain, operation, entities, confidence, risk_level, requires_confirmation.
def _parse_command(message: str, config_manager: ConfigManager) -> dict[str, Any]:
    with belief_scope('_parse_command'):
        logger.reason('Belief protocol reasoning checkpoint for _parse_command')
        text = message.strip()
        lower = text.lower()
        if any(phrase in lower for phrase in ['что ты умеешь', 'что умеешь', 'что ты можешь', 'help', 'помощь', 'доступные команды', 'какие команды']):
            logger.reflect('Belief protocol postcondition checkpoint for _parse_command')
            return {'domain': 'assistant', 'operation': 'show_capabilities', 'entities': {}, 'confidence': 0.98, 'risk_level': 'safe', 'requires_confirmation': False}
        dashboard_id = _extract_id(lower, ['(?:дашборд\\w*|dashboard)\\s*(?:id\\s*)?(\\d+)'])
        dashboard_ref = _extract_id(lower, ['(?:дашборд\\w*|dashboard)\\s*(?:id\\s*)?([a-zа-я0-9._-]+)'])
        dataset_id = _extract_id(lower, ['(?:датасет\\w*|dataset)\\s*(?:id\\s*)?(\\d+)'])
        task_id = _extract_id(lower, ['(task[-_a-z0-9]{1,}|[0-9a-f]{8}-[0-9a-f-]{27,})'])
        if any(k in lower for k in ['статус', 'status', 'state', 'проверь задачу']):
            logger.reflect('Belief protocol postcondition checkpoint for _parse_command')
            return {'domain': 'status', 'operation': 'get_task_status', 'entities': {'task_id': task_id}, 'confidence': 0.92 if task_id else 0.66, 'risk_level': 'safe', 'requires_confirmation': False}
        if any(k in lower for k in ['ветк', 'branch']) and any(k in lower for k in ['созд', 'сделай', 'create']):
            branch = _extract_id(lower, ['(?:ветк\\w*|branch)\\s+([a-z0-9._/-]+)'])
            logger.reflect('Belief protocol postcondition checkpoint for _parse_command')
            return {'domain': 'git', 'operation': 'create_branch', 'entities': {'dashboard_id': int(dashboard_id) if dashboard_id else None, 'branch_name': branch}, 'confidence': 0.95 if branch and dashboard_id else 0.7, 'risk_level': 'guarded', 'requires_confirmation': False}
        if any(k in lower for k in ['коммит', 'commit']):
            quoted = re.search('"([^"]{3,120})"', text)
            message_text = quoted.group(1) if quoted else 'assistant: update dashboard changes'
            logger.reflect('Belief protocol postcondition checkpoint for _parse_command')
            return {'domain': 'git', 'operation': 'commit_changes', 'entities': {'dashboard_id': int(dashboard_id) if dashboard_id else None, 'message': message_text}, 'confidence': 0.9 if dashboard_id else 0.7, 'risk_level': 'guarded', 'requires_confirmation': False}
        if any(k in lower for k in ['деплой', 'deploy', 'разверн']):
            env_match = _extract_id(lower, ['(?:в|to)\\s+([a-z0-9_-]+)'])
            is_dangerous = _is_production_env(env_match, config_manager)
            logger.reflect('Belief protocol postcondition checkpoint for _parse_command')
            return {'domain': 'git', 'operation': 'deploy_dashboard', 'entities': {'dashboard_id': int(dashboard_id) if dashboard_id else None, 'environment': env_match}, 'confidence': 0.92 if dashboard_id and env_match else 0.7, 'risk_level': 'dangerous' if is_dangerous else 'guarded', 'requires_confirmation': is_dangerous}
        if any(k in lower for k in ['миграц', 'migration', 'migrate']):
            src = _extract_id(lower, ['(?:с|from)\\s+([a-z0-9_-]+)'])
            tgt = _extract_id(lower, ['(?:на|to)\\s+([a-z0-9_-]+)'])
            dry_run = '--dry-run' in lower or 'dry run' in lower
            replace_db_config = '--replace-db-config' in lower
            fix_cross_filters = '--no-fix-cross-filters' not in lower
            is_dangerous = _is_production_env(tgt, config_manager)
            logger.reflect('Belief protocol postcondition checkpoint for _parse_command')
            return {'domain': 'migration', 'operation': 'execute_migration', 'entities': {'dashboard_id': int(dashboard_id) if dashboard_id else None, 'source_env': src, 'target_env': tgt, 'dry_run': dry_run, 'replace_db_config': replace_db_config, 'fix_cross_filters': fix_cross_filters}, 'confidence': 0.95 if dashboard_id and src and tgt else 0.72, 'risk_level': 'dangerous' if is_dangerous else 'guarded', 'requires_confirmation': is_dangerous or dry_run}
        if any(k in lower for k in ['бэкап', 'backup', 'резерв']):
            env_match = _extract_id(lower, ['(?:в|for|из|from)\\s+([a-z0-9_-]+)'])
            logger.reflect('Belief protocol postcondition checkpoint for _parse_command')
            return {'domain': 'backup', 'operation': 'run_backup', 'entities': {'dashboard_id': int(dashboard_id) if dashboard_id else None, 'environment': env_match}, 'confidence': 0.9 if env_match else 0.7, 'risk_level': 'guarded', 'requires_confirmation': False}
        if any(k in lower for k in ['здоровье', 'health', 'ошибки', 'failing', 'проблемы']):
            env_match = _extract_id(lower, ['(?:в|for|env|окружени[ея])\\s+([a-z0-9_-]+)'])
            logger.reflect('Belief protocol postcondition checkpoint for _parse_command')
            return {'domain': 'health', 'operation': 'get_health_summary', 'entities': {'environment': env_match}, 'confidence': 0.9, 'risk_level': 'safe', 'requires_confirmation': False}
        if any(k in lower for k in ['валидац', 'validate', 'провер']):
            env_match = _extract_id(lower, ['(?:в|for|env|окружени[ея])\\s+([a-z0-9_-]+)'])
            provider_match = _extract_id(lower, ['(?:provider|провайдер)\\s+([a-z0-9_-]+)'])
            logger.reflect('Belief protocol postcondition checkpoint for _parse_command')
            return {'domain': 'llm', 'operation': 'run_llm_validation', 'entities': {'dashboard_id': int(dashboard_id) if dashboard_id else None, 'dashboard_ref': dashboard_ref if dashboard_ref and (not dashboard_ref.isdigit()) else None, 'environment': env_match, 'provider': provider_match}, 'confidence': 0.88 if dashboard_id else 0.64, 'risk_level': 'guarded', 'requires_confirmation': False}
        if any(k in lower for k in ['документац', 'documentation', 'generate docs', 'сгенерируй док']):
            env_match = _extract_id(lower, ['(?:в|for|env|окружени[ея])\\s+([a-z0-9_-]+)'])
            provider_match = _extract_id(lower, ['(?:provider|провайдер)\\s+([a-z0-9_-]+)'])
            logger.reflect('Belief protocol postcondition checkpoint for _parse_command')
            return {'domain': 'llm', 'operation': 'run_llm_documentation', 'entities': {'dataset_id': int(dataset_id) if dataset_id else None, 'environment': env_match, 'provider': provider_match}, 'confidence': 0.88 if dataset_id else 0.64, 'risk_level': 'guarded', 'requires_confirmation': False}
        # ── Новые инструменты ────────────────────────────────────────
        if any(k in lower for k in ['список дашборд', 'покажи дашборд', 'найди дашборд', 'list dashboard', 'search dashboard', 'all dashboards', 'все дашборд']):
            env_match = _extract_id(lower, ['(?:в|for|env|окружени[ея])\\s+([a-z0-9_-]+)'])
            search_phrase = _extract_id(lower, ['(?:найди|search|поиск)\\s+([а-яa-z0-9_-]{2,})'])
            logger.reflect('Belief protocol postcondition checkpoint for _parse_command')
            return {'domain': 'dashboards', 'operation': 'search_dashboards', 'entities': {'environment': env_match, 'search': search_phrase}, 'confidence': 0.88 if env_match else 0.75, 'risk_level': 'safe', 'requires_confirmation': False}
        if any(k in lower for k in ['окружени', 'environment', 'среды', 'сред']):
            logger.reflect('Belief protocol postcondition checkpoint for _parse_command')
            return {'domain': 'environments', 'operation': 'list_environments', 'entities': {}, 'confidence': 0.9, 'risk_level': 'safe', 'requires_confirmation': False}
        if any(k in lower for k in ['обслуживан', 'maintenance', 'события']):
            logger.reflect('Belief protocol postcondition checkpoint for _parse_command')
            return {'domain': 'maintenance', 'operation': 'list_maintenance_events', 'entities': {}, 'confidence': 0.9, 'risk_level': 'safe', 'requires_confirmation': False}
        if any(k in lower for k in ['llm провайдер', 'llm provider', 'провайдеры']):
            logger.reflect('Belief protocol postcondition checkpoint for _parse_command')
            return {'domain': 'llm', 'operation': 'list_llm_providers', 'entities': {}, 'confidence': 0.9, 'risk_level': 'safe', 'requires_confirmation': False}
        if any(k in lower for k in ['llm статус', 'llm status', 'проверь llm', 'llm провер']):
            logger.reflect('Belief protocol postcondition checkpoint for _parse_command')
            return {'domain': 'llm', 'operation': 'get_llm_status', 'entities': {}, 'confidence': 0.9, 'risk_level': 'safe', 'requires_confirmation': False}
        logger.reflect('Belief protocol postcondition checkpoint for _parse_command')
        return {'domain': 'unknown', 'operation': 'clarify', 'entities': {}, 'confidence': 0.3, 'risk_level': 'safe', 'requires_confirmation': False}


# #endregion _parse_command


# #endregion AssistantCommandParser
