import argparse
from pathlib import Path

from .trade.cli import register_commands as register_trade
from .trade.cli import handle_command as handle_trade
from .copytrade.copy_cli import register_commands as register_copytrade
from .copytrade.copy_cli import handle_command as handle_copytrade
from .copytrade.monitor_cli import register_commands as register_monitor
from .copytrade.monitor_cli import handle_command as handle_monitor
from .copytrade.analyze_cli import register_commands as register_analyze
from .copytrade.analyze_cli import handle_command as handle_analyze
from .news.cli import register_commands as register_news
from .news.cli import handle_command as handle_news
from .shared.state_env import load_state_env


def _read_version_from_pyproject() -> str | None:
    """
    Best-effort fallback when package metadata is unavailable (e.g. running from source).
    """

    try:
        repo_root = Path(__file__).resolve().parents[2]
        pyproject = repo_root / "pyproject.toml"
        if not pyproject.exists():
            return None
        text = pyproject.read_text(encoding="utf-8")
        for line in text.splitlines():
            s = line.strip()
            if s.startswith("version"):
                # version = "0.6.0"
                parts = s.split("=", 1)
                if len(parts) != 2:
                    continue
                v = parts[1].strip().strip('"').strip("'")
                return v or None
    except Exception:
        return None
    return None


def _get_cli_version() -> str:
    try:
        from importlib.metadata import PackageNotFoundError, version

        try:
            return version("1m-trade")
        except PackageNotFoundError:
            pass
    except Exception:
        pass

    return _read_version_from_pyproject() or "unknown"


def main():
    parser = argparse.ArgumentParser(description="Hyperliquid SDK full-feature CLI (HIP-3 supported)")
    parser.add_argument("--testnet", action="store_true", help="Use testnet")
    parser.add_argument(
        "-v",
        "--version",
        action="version",
        version=_get_cli_version(),
        help="Show version and exit",
    )

    subparsers = parser.add_subparsers(dest="command", required=True)

    register_trade(subparsers)
    register_copytrade(subparsers)
    register_monitor(subparsers)
    register_analyze(subparsers)
    register_news(subparsers)

    args = parser.parse_args()
    needs_env = args.command not in {"copy", "monitor", "analyze", "news"}
    env_loaded = True
    if needs_env:
        env_loaded = load_state_env()

    if handle_copytrade(args):
        return
    if handle_monitor(args):
        return
    if handle_analyze(args):
        return
    if handle_news(args):
        return
    if handle_trade(parser=parser, args=args, env_loaded=env_loaded):
        return

    raise SystemExit(f"unknown command: {getattr(args, 'command', None)}")

if __name__ == "__main__":
    main()

