"""Command-line interface for the Tugsscript compiler."""

from __future__ import annotations

import argparse
from pathlib import Path
import runpy
import sys
import tempfile

from codely import TugsscriptError, compile_file, compile_source


def compile_command(source: str, output: str | None) -> int:
    target = compile_file(source, output)
    print(f"Хөрвүүллээ: {target}")
    return 0


def run_command(source: str) -> int:
    source_path = Path(source)
    if source_path.suffix != ".tugs":
        raise TugsscriptError("Ажиллуулах файл .tugs өргөтгөлтэй байна")
    compiled = compile_source(source_path.read_text(encoding="utf-8"), str(source_path))
    with tempfile.NamedTemporaryFile(
        mode="w", suffix=".py", encoding="utf-8", delete=False
    ) as generated:
        generated.write(compiled)
        temporary_path = Path(generated.name)
    try:
        runpy.run_path(str(temporary_path), run_name="__main__")
    finally:
        temporary_path.unlink(missing_ok=True)
    return 0


def repl_command() -> int:
    print("Tugsscript REPL. Нэг мөрийн илэрхийлэл бичнэ үү; гарах бол :гарах")
    environment: dict[str, object] = {}
    while True:
        try:
            line = input("ts> ")
        except (EOFError, KeyboardInterrupt):
            print()
            return 0
        if line.strip() == ":гарах":
            return 0
        try:
            compiled = compile_source(line)
            exec(compiled, environment, environment)
        except (TugsscriptError, Exception) as error:
            print(error, file=sys.stderr)


def parser() -> argparse.ArgumentParser:
    cli = argparse.ArgumentParser(description="Tugsscript (.tugs) compiler")
    subcommands = cli.add_subparsers(dest="command", required=True)
    compile_parser = subcommands.add_parser("compile", help=".tugs файлыг .py файл болгох")
    compile_parser.add_argument("source")
    compile_parser.add_argument("-o", "--output")
    run_parser = subcommands.add_parser("run", help=".tugs программыг хөрвүүлээд ажиллуулах")
    run_parser.add_argument("source")
    subcommands.add_parser("repl", help="нэг мөрийн интерактив горим")
    return cli


def main(argv: list[str] | None = None) -> int:
    arguments = list(sys.argv[1:] if argv is None else argv)
    if arguments and arguments[0].endswith(".tugs"):
        arguments.insert(0, "run")
    args = parser().parse_args(arguments)
    try:
        if args.command == "compile":
            return compile_command(args.source, args.output)
        if args.command == "run":
            return run_command(args.source)
        return repl_command()
    except TugsscriptError as error:
        print(f"TS алдаа: {error}", file=sys.stderr)
        return 1


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