"""CLI smoke test for Mira."""

from __future__ import annotations

import argparse
import os
import shutil
import subprocess
import sys
from mira.temp import make_temp_dir


def _write_file(path: str, content: str) -> None:
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, "w", encoding="utf-8") as handle:
        handle.write(content)


def _create_project(project_dir: str) -> None:
    pyproject = """
[project]
name = "smoke_engine"
version = "0.8.2"
description = "Mira smoke test project"
dependencies = []

[tool.mira]
include = "engine"
entry_point = "engine.main:run"
""".strip()

    _write_file(os.path.join(project_dir, "pyproject.toml"), pyproject)

    engine_dir = os.path.join(project_dir, "engine")
    _write_file(
        os.path.join(engine_dir, "__init__.py"),
        "VALUE = 123\n",
    )
    _write_file(
        os.path.join(engine_dir, "main.py"),
        "def run():\n    return 'ok'\n",
    )


def _run_command(
    command: list[str],
    cwd: str | None = None,
    verbose: bool = False,
) -> subprocess.CompletedProcess[str]:
    result = subprocess.run(command, cwd=cwd, capture_output=True, text=True)
    if verbose:
        if result.stdout:
            print(result.stdout)
        if result.stderr:
            print(result.stderr, file=sys.stderr)
    if result.returncode != 0:
        message = result.stderr.strip() or result.stdout.strip() or "command failed"
        raise RuntimeError(message)
    return result


def _run_build(project_dir: str, verbose: bool) -> str:
    command = [
        sys.executable,
        "-m",
        "mira.cli",
        "build",
        project_dir,
        "-o",
        "dist",
    ]
    result = _run_command(command, cwd=project_dir, verbose=verbose)
    lines = [line.strip() for line in result.stdout.splitlines() if line.strip()]
    mira_path = lines[-1] if lines else ""
    if not mira_path or not os.path.isfile(mira_path):
        raise RuntimeError("Build did not produce a .mira file")
    return mira_path


def _run_inspect(mira_path: str, verbose: bool) -> None:
    command = [sys.executable, "-m", "mira.cli", "inspect", mira_path]
    _run_command(command, verbose=verbose)


def main(argv: list[str] | None = None) -> int:
    """Run a CLI smoke test that builds and inspects a .mira archive."""
    parser = argparse.ArgumentParser(prog="mira-smoke")
    parser.add_argument("--keep", action="store_true", help="Keep temp files")
    parser.add_argument("--verbose", action="store_true", help="Show command output")
    args = parser.parse_args(argv)

    project_dir = make_temp_dir("mira_smoke_")
    try:
        _create_project(project_dir)
        mira_path = _run_build(project_dir, args.verbose)
        _run_inspect(mira_path, args.verbose)
        print(f"Smoke test passed: {mira_path}")
        if args.keep:
            print(f"Project kept at: {project_dir}")
        return 0
    except Exception as exc:
        print(f"Smoke test failed: {exc}", file=sys.stderr)
        if args.keep:
            print(f"Project kept at: {project_dir}")
        return 1
    finally:
        if not args.keep:
            shutil.rmtree(project_dir, ignore_errors=True)


if __name__ == "__main__":
    raise SystemExit(main())
