import json
import sys
from pathlib import Path

from whisper_client.main import WhisperClient


def cli():
    import argparse

    parser = argparse.ArgumentParser()

    parser.add_argument(
        "-k",
        "--api-key",
        type=str,
        required=True,
        help="API key for the whisper API"
    )

    parser.add_argument(
        "-s",
        "--api-scheme",
        type=str,
        default="https",
        help="API scheme for the whisper API"
    )

    parser.add_argument(
        "-H",
        "--api-host",
        type=str,
        default="whisper-api.example.com",
        help="API host for the whisper API"
    )

    parser.add_argument(
        "-p",
        "--api-port",
        type=int,
        default=443,  # 5464,
        help="API port for the whisper API"
    )

    parser.add_argument(
        "-u",
        "--api-url",
        type=str,
        default=None,
        help="API url for the whisper API"
    )

    parser.add_argument(
        "-A",
        "--audio-folder",
        type=str,
        default=None,
        help="Audio folder for the whisper API, allows the client to iterate over the files in the folder and send them to the API"
    )

    parser.add_argument(
        "-V",
        "--video-folder",
        type=str,
        default=None,
        help="Video folder for the whisper API, allows the client to iterate over the files in the folder and send them to the API"
    )

    parser.add_argument(
        "-T",
        "--text-folder",
        type=str,
        default=None,
        help="Text folder for the whisper API, if specified, the output text will be saved in this folder"
    )

    parser.add_argument(
        "-v",
        "--verbose",
        action="store_true",
        help="Verbose mode"
    )

    parser.add_argument(
        "-S",
        "--skip",
        action="store_true",
        help="Skip already downloaded files"
    )

    parser.add_argument(
        "-t",
        "--timeout",
        type=int,
        default=100,
        help="Timeout for the HTTP connexion"
    )

    parser.add_argument(
        "-i",
        "--interval",
        type=int,
        default=30,
        help="Interval between two status checks"
    )

    parser.add_argument(
        "-I",
        "--input",
        type=str,
        default=None,
        help="Input file to send to the API"
    )

    parser.add_argument(
        "-O",
        "--output",
        type=str,
        default=None,
        help="Output file to save the result"
    )

    parser.add_argument(
        "--stdout",
        action="store_true",
        help="Print the result to stdout"
    )

    parser.add_argument(
        "--stderr",
        action="store_true",
        help="Print the result to stderr"
    )

    parser.add_argument(
        "--no-verify",
        action="store_true",
        help="Do not verify the SSL certificate"
    )

    parser.add_argument(
        "-m",
        "--mode",
        type=str,
        default="full",
        help="Mode for the API, can be 'full', 'text', 'segments' and/or 'words'"
    )


    args = parser.parse_args()

    if args.verbose:
        print(args)

    if args.api_url is not None:
        api_scheme, api_host, api_port = args.api_url.split("://")[0], args.api_url.split("://")[1].split(":")[0], int(args.api_url.split("://")[1].split(":")[1])

    else:
        api_scheme, api_host, api_port = args.api_scheme, args.api_host, args.api_port

    wc = WhisperClient(
        api_key=args.api_key,
        api_scheme=api_scheme,
        api_host=api_host,
        api_port=api_port,
        audio_folder=args.audio_folder,
        video_folder=args.video_folder,
        text_folder=args.text_folder,
    )

    if args.input is not None:
        audiofile = Path(args.input)
        assert audiofile.exists(), f"ERROR : {audiofile} does not exist"

        hash_audio = wc.get_hash_audio(audiofile)

        if args.skip and wc.is_hash_done(hash_audio):
            print(f"Skipping {audiofile}")
            return 0

        wc.send_audio(audiofile)

        wc.wait_for_result()

        res = wc.get_result_with_mode(mode=args.mode)

        if args.output is not None:
            with open(args.output, "w", encoding="utf-8") as f:
                json.dump(res, f)

        if args.stdout:
            print(res)

        if args.stderr:
            print(res, file=sys.stderr)

    elif args.audio_folder is not None:
        raise NotImplementedError("audio_folder has not been implemented yet")

    elif args.video_folder is not None:
        raise NotImplementedError("video_folder has not been implemented yet")

    else:
        raise NotImplementedError("You must specify either an audio_folder or a video_folder")

    return 0


if __name__ == "__main__":
    cli()
