#!/usr/bin/env python3
import argparse
import json
import re
from pathlib import Path

import chevron

parser = argparse.ArgumentParser()
parser.add_argument('what', nargs='+')
parser.add_argument('--clone', '-c', default='uncapitalise')
args = parser.parse_args()
whats = args.what
clone = args.clone
init = Path(__file__).parent.parent / 'src' / 'remedapy' / '__init__.py'
init_text = init.read_text()
imports = set(re.findall(r'import (\w+)\n', init_text))
for what in whats:
    imports.add(what)
imports = sorted(imports)
new_init_text = ''
for x in imports:
    new_init_text += f'from .{x} import {x}\n'
new_init_text += '\n__all__ = [\n'
for x in imports:
    new_init_text += f"'{x}',\n"
new_init_text += ']\n'
print(new_init_text)
init.write_text(new_init_text)
for what in whats:
    print(what, clone)
    what_src_path = Path(__file__).parent.parent / 'src' / 'remedapy' / f'{what}.py'
    what_test_path = Path(__file__).parent.parent / 'src' / 'tests' / f'test_{what}.py'
    clone_src_path = Path(__file__).parent.parent / 'src' / 'remedapy' / f'{clone}.py'
    clone_test_path = Path(__file__).parent.parent / 'src' / 'tests' / f'test_{clone}.py'
    print(what_src_path.exists(), what_test_path.exists(), clone_src_path.exists(), clone_test_path.exists())
    if not what_src_path.exists():
        text = clone_src_path.read_text()
        text = text.replace(clone, what)
        print(text)
        what_src_path.write_text(text)
    if not what_test_path.exists():
        template = (Path(__file__).parent / 'test_template.mustache').read_text()
        print(template)
        remeda_text = (Path(__file__).parent.parent / 'typedoc-output.json').read_text()
        remeda_json = json.loads(remeda_text)
        camel_case_name = what.split('_')
        camel_case_name = [camel_case_name[0]] + [x.capitalize() for x in camel_case_name[1:]]
        camel_case_name = ''.join(camel_case_name)
        remeda_obj = next(x for x in remeda_json['children'] if x['name'] == camel_case_name)
        block_tags = [x['comment']['blockTags'] for x in remeda_obj['signatures']]
        data_first_tags = next(x for x in block_tags if any(y['tag'] == '@dataFirst' for y in x))
        data_last_tags = next(x for x in block_tags if any(y['tag'] == '@dataLast' for y in x))
        data_first_example = next(x for x in data_first_tags if x['tag'] == '@example')
        data_last_example = next(x for x in data_last_tags if x['tag'] == '@example')
        data_first = [x.strip().replace('; // => ', ' == ').replace(' // => ', ' == ').replace('; // ', ' == ').replace('; //=> ', ' == ').replace(' // ', ' == ').replace(camel_case_name, what) for x in data_first_example['content'][0]['text'].split("\n") if '```' not in x]
        data_last = [x.strip().replace('; // => ', ' == ').replace(' // => ', ' == ').replace('; // ', ' == ').replace('; //=> ', ' == ').replace(' // ', ' == ').replace(camel_case_name, what) for x in data_last_example['content'][0]['text'].split("\n") if '```' not in x]
        data_first_signature_block = next(x for x in data_first_tags if x['tag'] == '@signature')
        data_last_signature_block = next(x for x in data_last_tags if x['tag'] == '@signature')
        data_first_signature = data_first_signature_block['content'][0]['text'].strip().replace(camel_case_name, what)
        data_last_signature = data_last_signature_block['content'][0]['text'].strip().replace(camel_case_name, what)
        x = chevron.render(template=template, data={
            'title': camel_case_name[0].upper() + camel_case_name[1:],
            'data_first': data_first,
            'data_last': data_last,
            'data_first_signature': data_first_signature,
            'data_last_signature': data_last_signature,
        })
        print(x)
        what_test_path.write_text(x)
