from .database import *
from .s23_options_util import get_option_schema, get_option_v3_schema, generate_v2, generate_v3


def _parse_v2(v2_lines: list[str]) -> dict[str, str]:
    cs_v2 = g_update_prefix | { 'type' : 'option' }
    for s in v2_lines:
        tokens = s.split()
        if tokens[0].upper() == 'PATTERN': # can not upper id
            value = tokens[1] if len(tokens) > 1 else ''
            cs_v2 |= { 'PATTERN' : value }
        elif tokens[0].upper() == 'QUALITY': # can not upper trace node
            value = tokens[1]
            if len(tokens) > 2:
                value += f' {tokens[2]}'
            cs_v2 |= { 'QUALITY' : value }
        else:
            line = s.upper().strip()
            for key in get_option_schema('').keys():
                if line.startswith(key):
                    value = line.removeprefix(key).strip()
                    cs_v2 |= { key : value }
    return cs_v2


def _inp_in_option_v3(section: list[str]) -> ChangeSet:
    if len(section) <= 0:
        return ChangeSet()

    cs_v3 = g_update_prefix | { 'type' : 'option_v3' }
    v2_lines = []
    for s in section:
        if s.startswith(';'):
            continue

        tokens = s.strip().split()
        key = tokens[0]
        if key in get_option_v3_schema('').keys():
            value = ''
            if len(tokens) == 2:
                value = tokens[1]
            elif len(tokens) > 2:
                value = ' '.join(tokens[1:])
            cs_v3 |= { key : value }
        else:
            v2_lines.append(s.strip())

    # unlikely...
    cs_v2 = _parse_v2(v2_lines)

    result = ChangeSet(cs_v3)
    result.merge(generate_v3(ChangeSet(cs_v2)))
    result.merge(generate_v2(result))
    return result


def inp_in_option_v3(section: list[str]) -> str:
    sql = ''
    result = _inp_in_option_v3(section)
    for op in result.operations:
        for key in op.keys():
            if key == 'operation' or key == 'type':
                continue
            if op['type'] == 'option_v3':
                sql += f"update options_v3 set value = '{op[key]}' where key = '{key}';"
            else:
                sql += f"update options set value = '{op[key]}' where key = '{key}';"
    return sql


def inp_out_option_v3(name: str) -> list[str]:
    lines = []
    objs = read_all(name, f"select * from options_v3")
    for obj in objs:
        key = obj['key']
        value = obj['value']
        if str(value).strip() != '':
            lines.append(f'{key} {value}')
    return lines
