import os
import argparse
import webbrowser
import tempfile
import shutil

from .cola_parser import Parser
from .problem import EmptyException
from .util import *

def run_coso(file=None, cola=None, debug=False):
    """

    """
    parser = Parser(file, cola)
    try:
        parser.parse()
        sol = parser.problem.solve(debug=debug)
        return str(sol)
    except EmptyException:
        print("Could not find a problem :(")


def run_viscoso(
    file=None, 
    cola=None, 
    visual=tempfile.NamedTemporaryFile(delete=False, suffix='.html').name):
    """

    Args:
        file (str, optional): a path to a file containing a CoLa program. Defaults to None.
        cola (str, optional): a CoLa program. Defaults to None.
        visual (str, optional): a path where the html representation should be saved. Defaults to a temporary file
    Returns:
        str: the html string generated by VisCoSo
    """
    parser = Parser(file, cola)
    try:
        parser.parse()
        sol = parser.problem.solve(debug=False)
        with open(visual, "w+") as out:
            out.write(sol.log.to_viscoso())
            webbrowser.open(visual, new=2)
        return str(sol)
    except EmptyException:
        print("Could not find a problem :(")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("filename", help="Run solver on CoLa file")
    parser.add_argument(
        "-v",
        nargs='?',
        const=os.path.join("src", "VisCoSo", "viscoso.html"),
        help="Generate a visual representation of CoSo reasoning to an html file",
    )
    parser.add_argument("--debug", action="store_true", help="Print log")
    args = parser.parse_args()
    if args.filename:
        print("Running solver...")
        if args.v:
            sol = run_viscoso(file=args.filename, visual=args.v)
        else:
            sol = run_coso(file=args.filename, debug=args.debug)
        print(f"Solution: {sol}")
    else:
        parser.print_help()
