"""
JetBrains IDE Integration

Provides configuration for JetBrains IDEs (PyCharm, IntelliJ, etc.)
"""

import logging
from dataclasses import dataclass, field
from typing import Any

from groknroll.ide.base import IDEConfig, IDEType, IntegrationResult

logger = logging.getLogger(__name__)


@dataclass
class JetBrainsPlugin:
    """JetBrains plugin recommendation"""

    id: str
    name: str
    description: str = ""
    required: bool = False


@dataclass
class JetBrainsConfig:
    """JetBrains specific configuration"""

    run_configurations: list[dict[str, Any]] = field(default_factory=list)
    external_tools: list[dict[str, Any]] = field(default_factory=list)
    plugins: list[JetBrainsPlugin] = field(default_factory=list)


def generate_jetbrains_settings(config: IDEConfig) -> dict[str, str]:
    """Generate JetBrains settings XML files"""
    cmd = config.groknroll_path or "groknroll"

    run_configs = f'''<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectRunConfigurationManager">
    <configuration name="groknroll: TUI" type="ShConfigurationType">
      <option name="SCRIPT_PATH" value="{cmd}" />
      <option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
    </configuration>
    <configuration name="groknroll: Build" type="ShConfigurationType">
      <option name="SCRIPT_PATH" value="{cmd}" />
      <option name="SCRIPT_OPTIONS" value="build" />
      <option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
    </configuration>
  </component>
</project>'''

    tools = f'''<?xml version="1.0" encoding="UTF-8"?>
<toolSet name="groknroll">
  <tool name="Open TUI" program="{cmd}" description="Open groknroll TUI" />
  <tool name="Build Agent" program="{cmd}" parameters="build" />
  <tool name="Oracle" program="{cmd}" parameters="oracle" />
  <tool name="Analyze" program="{cmd}" parameters="analyze $FilePath$" />
</toolSet>'''

    return {"runConfigurations.xml": run_configs, "tools/External Tools.xml": tools}


def setup_jetbrains_integration(config: IDEConfig, **kwargs) -> IntegrationResult:
    """Setup JetBrains IDE integration"""
    idea_dir = config.project_root / ".idea"
    idea_dir.mkdir(exist_ok=True)
    files_created = []

    try:
        settings = generate_jetbrains_settings(config)
        for filename, content in settings.items():
            file_path = idea_dir / filename
            file_path.parent.mkdir(exist_ok=True)
            file_path.write_text(content)
            files_created.append(file_path)

        return IntegrationResult(
            success=True,
            ide_type=IDEType.JETBRAINS,
            files_created=files_created,
            message=f"JetBrains integration setup in {idea_dir}",
        )
    except Exception as e:
        return IntegrationResult(success=False, ide_type=IDEType.JETBRAINS, error=str(e))
