"""Core logic for the ``mld info`` command."""

from __future__ import annotations

import argparse
import json
import os
import sys
from pathlib import Path

from mld_sdk._discover import DiscoveredPlugin, discover_plugin, get_sdk_dependency_spec


def _supports_color() -> bool:
    """Return True if stdout likely supports ANSI color."""
    if os.environ.get("NO_COLOR"):
        return False
    if not sys.stdout.isatty():
        return False
    if os.environ.get("TERM") == "dumb":
        return False
    return True


def _format_info(
    plugin: DiscoveredPlugin, sdk_spec: str | None, color: bool
) -> str:
    """Format plugin metadata as a human-readable string."""
    # Header line
    version_suffix = f" v{plugin.project_version}" if plugin.project_version else ""
    header = f"{plugin.project_name}{version_suffix}"
    if color:
        header = f"\033[1m{header}\033[0m"

    description = plugin.project_description or "(no description)"

    # Infer type from class name
    plugin_type = (
        "experiment-design" if "ExperimentDesign" in plugin.class_name else "analysis"
    )

    entry_point = f"{plugin.module_path}:{plugin.class_name}"
    sdk_requires = sdk_spec or "(not specified)"
    frontend = "yes" if plugin.has_frontend else "no"

    lines = [
        f"  {header}",
        f"  {description}",
        "",
        f"  {'Type':<14}{plugin_type}",
        f"  {'Entry point':<14}{entry_point}",
        f"  {'Routes':<14}{plugin.routes_prefix}",
        f"  {'SDK requires':<14}{sdk_requires}",
        f"  {'Frontend':<14}{frontend}",
    ]
    return "\n".join(lines)


def cmd_info(args: argparse.Namespace) -> None:
    """Execute the ``mld info`` command."""
    project_dir = Path(args.path).resolve()
    plugin = discover_plugin(project_dir)
    sdk_spec = get_sdk_dependency_spec(project_dir)

    if args.json_output:
        data = {
            "name": plugin.project_name,
            "version": plugin.project_version,
            "description": plugin.project_description,
            "entry_point_name": plugin.entry_point_name,
            "module_path": plugin.module_path,
            "class_name": plugin.class_name,
            "routes_prefix": plugin.routes_prefix,
            "has_frontend": plugin.has_frontend,
            "sdk_requires": sdk_spec,
        }
        print(json.dumps(data, indent=2))
    else:
        print(_format_info(plugin, sdk_spec, _supports_color()))
