#!/bin/python

import subprocess
import re

# Dictionary for symbol conversion to LaTeX format
latex_symbols = {
    "Ω": r"\Omega",
    "ohm": r"\Omega",
    "A": r"\text{A}",
    "V": r"\text{V}",
    "milliamperes": r"\text{mA}",
    "*": r"\cdot",
    "N*m": r"\text{N} \cdot \text{m}",
    "in*lb": r"\text{in} \cdot \text{lb}",
    "||": r"\|",
    "−": r"-",
    "μ": r"\mu",
    "−": r"-",
}


def run_qalc(expression):
    # Run qalc with the provided expression
    result = subprocess.run(["qalc", expression], stdout=subprocess.PIPE, text=True)
    output = result.stdout
    return output


def format_expression_for_latex(expression):
    # Replace the units and special characters in the input expression using the dictionary
    for symbol, latex_symbol in latex_symbols.items():
        expression = expression.replace(symbol, latex_symbol)

    return expression


def format_result_for_latex(output):
    # Get the last line of qalc output (the answer)
    output = output.strip().split("\n")[-1]

    # Check if the result is approximate (contains "≈")
    approx_match = "≈" in output

    # Extract the value and unit from the result
    match = re.search(r"(≈|=)\s*([-\d\.]+)\s*(.*)", output)
    if match:
        _, value, unit = match.groups()
        # Replace the units and special characters using the dictionary
        unit = unit.strip()
        for symbol, latex_symbol in latex_symbols.items():
            unit = unit.replace(symbol, latex_symbol)

        # Use = or \approx in LaTeX based on whether the result is approximate
        equal_symbol = r"\approx" if approx_match else "="

        # Only add \, if there's a unit
        if unit:
            latex_result = f"{equal_symbol} {value.strip()} \\, {unit}"
        else:
            latex_result = f"{equal_symbol} {value.strip()}"

        return latex_result
    return output  # Fallback to returning the raw qalc output if no match


def copy_to_clipboard(text):
    # Use wl-copy to send the text to the clipboard
    subprocess.run(["wl-copy"], input=text, text=True)


def main():
    try:
        while True:
            # Input the qalc expression
            expression = input("\nEnter qalc expression (Ctrl+C to exit): ")

            # Run qalc and get the result
            qalc_output = run_qalc(expression)

            # Format the input expression for LaTeX
            latex_expression = format_expression_for_latex(expression)

            # Format the output result for LaTeX
            latex_result = format_result_for_latex(qalc_output)

            # Combine both input expression and result for final LaTeX output
            final_latex_output = f"{latex_expression} {latex_result}"

            # Print and copy to clipboard
            print(f"Final LaTeX output:\n{final_latex_output}")
            copy_to_clipboard(final_latex_output)
            print("LaTeX result copied to clipboard!")

    except KeyboardInterrupt:
        print("\nExiting...")


if __name__ == "__main__":
    main()
