#!/usr/bin/env python

from sensei import Api, ApiError
from importlib.metadata import version
from datetime import datetime, timezone
import argparse
import os
import sys
import json

CONF_PATH = os.path.expanduser("~/.sensei")


def get_conf():
    if os.path.isfile(CONF_PATH):
        return json.load(open(CONF_PATH))
    return {}

def write_conf(conf):
    json.dump(conf, open(CONF_PATH, "w"), indent=4)


def fmt_time(value):
    """ISO timestamp from the API as YYYY-MM-DD HH:MM in UTC"""
    if not value:
        return "-"
    when = datetime.fromisoformat(value.replace("Z", "+00:00"))
    return when.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M")


def fmt_duration(seconds):
    if seconds is None:
        return "-"
    minutes, seconds = divmod(round(seconds), 60)
    hours, minutes = divmod(minutes, 60)
    return f"{hours}:{minutes:02}:{seconds:02}" if hours else f"{minutes}:{seconds:02}"


def fmt_text(value, width=30):
    if not value:
        return "-"
    return value if len(value) <= width else value[:width - 1] + "…"


def print_table(headers, rows):
    widths = [max(len(str(cell)) for cell in column) for column in zip(headers, *rows)]
    for row in [headers, *rows]:
        print("  ".join(str(cell).ljust(width) for cell, width in zip(row, widths)).rstrip())


def print_listing(kind, count, results, limit, as_json, headers, to_row):
    """Prints up to `limit` (0 for all) of a listing's `results`, as a table or JSON"""
    shown = [r for _, r in zip(range(limit), results)] if limit else list(results)
    if as_json:
        print(json.dumps(shown, indent=2))
        return shown
    if shown:
        print_table(headers, [to_row(r) for r in shown])
        print()
    print(f"{len(shown)} of {count} {kind}" + (" (use --limit to show more)" if len(shown) < count else ""))
    return shown


def episode_row(e):
    return [e["id"], e["name"] or "-", fmt_time(e["collected_at"]), e["device"], fmt_text(e["operator"], 20),
            fmt_text(e["task"]), fmt_duration(e["length_seconds"]), e["status"]]


def session_row(s):
    return [s["id"], fmt_time(s["start_time"]), s["device"], fmt_text(s["operator"], 20),
            fmt_text(s["task"] and s["task"]["description"]), s["num_episodes"],
            fmt_duration(s["total_length_seconds"]), "yes" if s["active"] else ""]


if  __name__=='__main__':
    parser = argparse.ArgumentParser(f"Sensei Robotics CLI v{version('sensei-cli')}")
    parser.add_argument("--version", action="version", version=f"%(prog)s {version('sensei-cli')}")
    parser.add_argument("--key", help="Set global API Key")
    parser.add_argument("--ls", metavar="PATH", nargs="?", const="/", help="List contents of given path")
    parser.add_argument("-i", "--interactive", action="store_true", help="Interactive mode")
    parser.add_argument("-o", "--out", metavar="DIR", default="sensei-data", help="Directory to write files to")
    parser.add_argument("-d", "--download", metavar="PATH", nargs="?", const="/", help="Download resource at given path."
                        " If no argument given, download everything. To download directory, use --recursive."
                        " With --episodes/--sessions, download the listed episodes/sessions instead")
    parser.add_argument("-r", "--recursive", action="store_true", help="Recursively download files in given directory."
                        " Use in conjunction with --download")
    parser.add_argument("-w", "--overwrite", action="store_true", help="Overwrite existing files in destination dir")
    parser.add_argument("--episodes", action="store_true", help="List collection episodes, most recently collected first")
    parser.add_argument("--sessions", action="store_true", help="List collection sessions, newest first")
    parser.add_argument("--download-episode", metavar="ID", help="Download all output files of the given episode")
    parser.add_argument("--download-session", metavar="ID",
                        help="Download all output files of every episode in the given session")

    listing = parser.add_argument_group("--episodes/--sessions options")
    listing.add_argument("--device", metavar="NAME", help="Only those from this device")
    listing.add_argument("--operator", metavar="NAME", help="Only those by this operator (name or ID)")
    listing.add_argument("--task", metavar="TEXT", help="Only those of this task (description or ID)")
    listing.add_argument("--session", metavar="ID", help="Only episodes in this session (--episodes only)")
    listing.add_argument("--status", choices=Api.EPISODE_STATUSES,
                         help="Only episodes with this processing status (--episodes only)")
    listing.add_argument("--active", action="store_true",
                         help="Only sessions still open to new episodes (--sessions only)")
    listing.add_argument("--day", metavar="YYYY-MM-DD", help="Only those collected on this day")
    listing.add_argument("--tz", metavar="TZ", help="Timezone of --day, e.g. America/Los_Angeles (default UTC)")
    listing.add_argument("--order-by", metavar="FIELD",
                         help="Sort by FIELD, comma-separate several, prefix with - for descending,"
                         f" e.g. --order-by=-length_seconds. Episodes: {', '.join(Api.EPISODE_ORDERING_FIELDS)}."
                         f" Sessions: {', '.join(Api.SESSION_ORDERING_FIELDS)}")
    listing.add_argument("-n", "--limit", type=int, default=50, help="Show at most this many (default 50, 0 for all)")
    listing.add_argument("--json", action="store_true", help="Print results as JSON")

    args = parser.parse_args()

    if args.episodes and args.sessions:
        parser.error("use only one of --episodes and --sessions")
    if args.sessions and (args.session or args.status):
        parser.error("--session and --status only apply to --episodes")
    if args.episodes and args.active:
        parser.error("--active only applies to --sessions")
    if (args.episodes or args.sessions) and args.download not in (None, "/"):
        parser.error("--download takes no PATH with --episodes/--sessions")
    if args.order_by:
        allowed = Api.SESSION_ORDERING_FIELDS if args.sessions else Api.EPISODE_ORDERING_FIELDS
        for field in args.order_by.split(","):
            if field.lstrip("-") not in allowed:
                parser.error(f"can't order by {field.lstrip('-')!r}, choose from {', '.join(allowed)}")

    conf = get_conf()

    if args.key:
        print("Writing API key to", CONF_PATH)
        conf["key"] = args.key
        write_conf(conf)
        exit()
    
    destination_path = os.path.abspath(args.out)

    if not conf.get("key"):
        print("No API Key found")
        conf["key"] = input("Enter your API Key: ").strip()
        if not conf["key"]:
            exit()
        write_conf(conf)
        exit()
    
    api = Api(conf["key"], destination=destination_path)

    if args.interactive:
        print("Entering interactive mode. Type 'help' for help, 'exit' to exit")
        while True:
            try:
                cmd = input("sensei> ").strip()
                if cmd in ("exit", "quit"):
                    break
                elif cmd == "help":
                    print("Commands:")
                    print("  ls [PATH]          List contents of given path (default /)")
                    print("  download PATH      Download file at given path")
                    print("  rdownload PATH    Recursively download all files in given directory")
                    print("  exit, quit        Exit interactive mode")
                    print("  help              Show this help message")
                elif cmd.startswith("ls"):
                    parts = cmd.split(maxsplit=1)
                    path = parts[1] if len(parts) > 1 else "/"
                    result_count = 0
                    for e in api.iter_dirs(path):
                        print("(DIR)", e["path"])
                        result_count += 1
                    for e in api.iter_files(path):
                        print(e["filename"])
                        result_count += 1

                    print()
                    print(result_count, "results")
                elif cmd.startswith("download"):
                    parts = cmd.split(maxsplit=1)
                    if len(parts) < 2:
                        print("Error: download command requires a PATH argument")
                        continue
                    path = parts[1]
                    print(f"Downloading file {path} into {destination_path}...")
                    try:
                        api.download_file_from_path(path, overwrite=args.overwrite)
                    except FileNotFoundError:
                        print("Warning: file not found")
                elif cmd.startswith("rdownload"):
                    parts = cmd.split(maxsplit=1)
                    if len(parts) < 2:
                        print("Error: rdownload command requires a PATH argument")
                        continue
                    path = parts[1]
                    print(f"Recursively downloading from {path} into {destination_path}...")
                    file_found = api.recursive_download(path=path, overwrite=args.overwrite)
                    if not file_found:
                        print("Warning: folder is empty or doesn't exist")
                elif cmd == "":
                    continue
                else:
                    print("Unknown command:", cmd)
            except EOFError:
                print()
                break
            except KeyboardInterrupt:
                print("\nInterrupted")
                continue
        exit()

    if args.download and not (args.episodes or args.sessions):
        try:
            if args.recursive:
                print(f"Recursively downloading from {args.download} into {destination_path}...")
                file_found = api.recursive_download(path=args.download, overwrite=args.overwrite)
                if not file_found:
                    print("Warning: folder is empty or doesn't exist")
            else:
                print(f"Downloading file {args.download} into {destination_path}...")
                try:
                    api.download_file_from_path(args.download, overwrite=args.overwrite)
                except FileNotFoundError:
                    print("Warning: file not found")
        except KeyboardInterrupt:
            print("\nInterrupted, partial downloads cleaned up")
            exit(130)
        exit()

    try:
        if args.episodes:
            count, results = api.list_episodes(
                device=args.device, session=args.session, operator=args.operator, task=args.task,
                status=args.status, day=args.day, tz=args.tz, ordering=args.order_by,
            )
            episodes = print_listing(
                "episodes", count, results, args.limit, args.json,
                ["ID", "NAME", "COLLECTED (UTC)", "DEVICE", "OPERATOR", "TASK", "LENGTH", "STATUS"], episode_row,
            )
            if args.download and episodes:
                print(f"\nDownloading {len(episodes)} episodes into {destination_path}...", file=sys.stderr)
                if not api.download_episodes(episodes, overwrite=args.overwrite):
                    print("Warning: none of these episodes has output to download yet", file=sys.stderr)
            exit()

        if args.sessions:
            count, results = api.list_sessions(
                device=args.device, operator=args.operator, task=args.task, active=args.active,
                day=args.day, tz=args.tz, ordering=args.order_by,
            )
            sessions = print_listing(
                "sessions", count, results, args.limit, args.json,
                ["ID", "START (UTC)", "DEVICE", "OPERATOR", "TASK", "EPISODES", "LENGTH", "ACTIVE"], session_row,
            )
            if args.download and sessions:
                print(f"\nDownloading {len(sessions)} sessions into {destination_path}...", file=sys.stderr)
                if not api.download_sessions(sessions, overwrite=args.overwrite):
                    print("Warning: no episode in these sessions has output to download yet", file=sys.stderr)
            exit()

        if args.download_episode:
            print(f"Downloading episode {args.download_episode} into {destination_path}...")
            api.download_episode(args.download_episode, overwrite=args.overwrite)
            exit()

        if args.download_session:
            print(f"Downloading session {args.download_session} into {destination_path}...")
            if not api.download_session(args.download_session, overwrite=args.overwrite):
                print("Warning: no episode in this session has output to download yet")
            exit()
    except (ApiError, LookupError) as e:
        print("Error:", e)
        exit(1)
    except KeyboardInterrupt:
        print("\nInterrupted, partial downloads cleaned up")
        exit(130)

    if args.ls:
        result_count = 0
        for e in api.iter_dirs(args.ls):
            print("(DIR)", e["path"])
            result_count += 1
        for e in api.iter_files(args.ls):
            print(e["filename"])
            result_count += 1
        
        print()
        print(result_count, "results")

        exit()

    parser.print_help()





