#!/usr/bin/env python3
"""Drive the shared editor core over fixture files.

Usage: editor_driver.py SHARED_DIR (MODE INFILE OUTFILE)...

MODE is `indent`, `align` (call the shared core's API), or `indent-cli`,
`align-cli` (run the same operation through the core's command-line
interface, as the Vim plugin does).  Each triple applies that tool to INFILE
and writes the result to OUTFILE.  Also asserts the built-in error paths
(no enclosing table; empty `check` output on balanced fixtures).
Called by editor_test.sh; exits nonzero on an internal error.
"""

import subprocess
import sys


def apply_indent(KE, s):
    return KE.indent_text(s)


def apply_align(KE, s):
    caret = s.index('|') if '|' in s else 0
    return KE.align_text(s, caret)[0]


def line_col_of_first_bar(s):
    pos = s.index('|') if '|' in s else 0
    line = s.count('\n', 0, pos) + 1
    col = pos - (s.rfind('\n', 0, pos) + 1) + 1
    return line, col


def run_cli(script, args, s):
    r = subprocess.run([sys.executable, script] + args,
                       input=s.encode('utf-8'), stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE)
    if r.returncode != 0:
        sys.exit("editor_driver.py: CLI failed: %s" % r.stderr.decode())
    return r.stdout.decode('utf-8')


def main():
    shared_dir = sys.argv[1]
    sys.path.insert(0, shared_dir)
    import klammertext_edit as KE
    script = shared_dir + '/klammertext_edit.py'

    args = sys.argv[2:]
    for k in range(0, len(args), 3):
        mode, infile, outfile = args[k:k + 3]
        with open(infile) as f:
            s = f.read()
        if mode == 'indent':
            out = apply_indent(KE, s)
        elif mode == 'align':
            out = apply_align(KE, s)
        elif mode == 'indent-cli':
            out = run_cli(script, ['indent'], s)
        elif mode == 'align-cli':
            line, col = line_col_of_first_bar(s)
            out = run_cli(script, ['align', str(line), str(col)], s)
        else:
            sys.exit("editor_driver.py: unknown mode: " + mode)
        with open(outfile, 'w') as f:
            f.write(out)

    # Error and diagnostics paths.
    assert KE.enclosing_span("no table here\n", 3, KE.ALIGN_KLAMMERS) is None
    assert KE.diagnostics("@i abc @ #[ x ]# ^@\n") == []
    probs = KE.diagnostics("@i abc\n@ol x ul@\n")
    assert any('never closed' in p['message'] for p in probs), probs
    assert any('ul@' in p['message'] for p in probs), probs
    assert run_cli(script, ['check'], "@i abc @\n") == ""
    assert '1:1:' in run_cli(script, ['check'], "@i abc\n")


if __name__ == '__main__':
    main()
