# zeska.py
"""
ZeskaLang main module (v0.5.0)
Provides:
 - __version__
 - a simple CLI: `zeska` (REPL or run file)
 - functions: repl(), run_file(path)
"""

__version__ = "0.5.0"

import sys
import argparse
import code
from pathlib import Path

PROMPT = "zeska> "

def run_line(line: str):
    """
    TODO: Replace this stub with your parser/exec logic.
    For now, it just echoes input with a mock result.
    """
    # Basic example: pretend lines starting with 'print' print
    line = line.strip()
    if not line:
        return None
    if line.startswith("print "):
        expr = line[len("print "):]
        # naive echo, you would evaluate/excute real Zeska logic here
        result = expr
        print(result)
        return result
    # fallback: just echo
    print(f"[zeska echo] {line}")
    return line

def run_file(path: str):
    p = Path(path)
    if not p.exists():
        raise FileNotFoundError(path)
    text = p.read_text(encoding="utf-8")
    # simple: run line by line
    for line in text.splitlines():
        run_line(line)

def repl():
    """
    Interactive REPL loop. Use basic history through readline if available.
    """
    try:
        import readline
        histfile = Path.home() / ".zeska_history"
        try:
            readline.read_history_file(str(histfile))
        except FileNotFoundError:
            pass
    except Exception:
        readline = None

    print("Zeska interactive shell (v{})".format(__version__))
    print("Type '.exit' or Ctrl-D to quit. Use 'run <file>' to run a file.")
    while True:
        try:
            line = input(PROMPT)
        except EOFError:
            print()
            break
        if not line:
            continue
        if line.strip() in (".exit", "exit", "quit"):
            break
        if line.startswith("run "):
            _, fname = line.split(" ", 1)
            try:
                run_file(fname.strip())
            except Exception as e:
                print("Error running file:", e)
            continue
        try:
            run_line(line)
        except Exception as e:
            print("Error:", e)
    # save history
    if readline:
        try:
            readline.write_history_file(str(histfile))
        except Exception:
            pass

def main():
    parser = argparse.ArgumentParser(prog="zeska", description="Zeska language CLI (v{})".format(__version__))
    parser.add_argument("--version", action="store_true", help="Print version and exit")
    parser.add_argument("--run", "-r", metavar="FILE", help="Run a .zeska file and exit")
    parser.add_argument("--debug", action="store_true", help="Enable debug mode")
    parser.add_argument("--format", choices=["plain","pretty"], default="pretty", help="Output format")
    args = parser.parse_args()

    if args.version:
        print(__version__)
        return 0

    if args.run:
        try:
            run_file(args.run)
        except Exception as e:
            print("Error:", e, file=sys.stderr)
            return 2
        return 0

    # Default: interactive REPL
    repl()
    return 0

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