import argparse
import asyncio
import subprocess
import os
import sys

import dotenv
dotenv.load_dotenv()

def main_cli():
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers()

    recorder_command = subparsers.add_parser("record", help="Tool to record data about pages you visit")
    recorder_command.add_argument("url", default="app.development.hirelogic.com", help="Page to open in browser and start recording")
    recorder_command.add_argument("--out", "-o", default="output", help="Name of the directory where recording files are stored. After finishing recording, this directory is zipped. Defaults to \"output\"", required=False)
    recorder_command.add_argument("--format", "-f", default="sdiff", choices=["full", "sdiff"], help='Format of output snapshots. Use "full" for complete snapshots (more data) or "sdiff" for snapshot of initial state with list of differences against that state.')
    recorder_command.add_argument("--development", "-d", action="store_true", help="Enable development mode where browser script is rebuilt on each run.")
    browser_group = recorder_command.add_mutually_exclusive_group(required=False)
    browser_group.add_argument("--browser-path", help="Absolute path to the browser executable")
    browser_group.add_argument("--browser-port", help="Port on which we can connect to browser using CDP")
    recorder_command.set_defaults(subcommand="record")

    playwright_command = subparsers.add_parser("playwright", help='Passes through commands to "playwright"', add_help=False)
    playwright_command.add_argument("command", nargs='*', help="Playwright command")
    playwright_command.set_defaults(subcommand="playwright")

    args, rest = parser.parse_known_args()

    if not "subcommand" in args:
        parser.print_help()
        sys.exit()

    if args.subcommand == "record":
        try:
            from caserunner.recorder import Recorder
            asyncio.run(Recorder(
                start_url=args.url,
                output_path=args.out,
                browser_path=args.browser_path if "browser_path" in args else None,
                browser_cdp=args.browser_port if "browser_port" in args else None,
                format=args.format,
                development=args.development if "development" in args else False
            ).run())
        except KeyboardInterrupt:
            print(f"Keyboard interrupt received. To stop the recording correctly, please close the browser instead. The recording is stoped, but the output will not be zipped. Please manually zip {args.out or 'output'} directory if needed.")

    elif args.subcommand == "playwright":
        try:
            env = os.environ.copy()
            env["PW_LANG_NAME"] = "python"
            env["PW_LANG_NAME_VERSION"] = f"{sys.version_info.major}.{sys.version_info.minor}"
            #subprocess.run(["node.exe", "package/cli.js", *args.command, *rest], env=env, cwd="./.venv/Lib/site-packages/playwright/driver/", check=True, shell=True)
            subprocess.run(["playwright", *args.command, *rest], env=env, check=True, shell=True)
        except:
            pass

if __name__ == "__main__":
    from caserunner.recorder import Recorder
    asyncio.run(Recorder(start_url="https://app.development.hirelogic.com", development=True).run())