import io


def generate_table_definition(schema_and_table, column_info,
                              primary_key=None, foreign_keys=None,
                              diststyle=None, distkey=None, sortkey=None):
    """Return a CREATE TABLE statement as a string."""
    if not column_info:
        raise Exception('No columns specified for {}'.format(schema_and_table))

    out = io.StringIO()

    out.write('CREATE TABLE {} (\n'.format(schema_and_table))

    columns_count = len(column_info)
    for i, (column, type_) in enumerate(column_info):
        out.write('    "{}" {}'.format(column, type_))
        if (i < columns_count - 1) or primary_key or foreign_keys:
            out.write(',')
        out.write('\n')

    if primary_key:
        out.write('    PRIMARY KEY({})'.format(primary_key))
        if foreign_keys:
            out.write(',')
        out.write('\n')

    foreign_keys = foreign_keys or []
    foreign_keys_count = len(foreign_keys)
    for i, (key, reftable, refcolumn) in enumerate(foreign_keys):
        out.write('    FOREIGN KEY({}) REFERENCES {}({})'.format(
            key, reftable, refcolumn
        ))
        if i < foreign_keys_count - 1:
            out.write(',')
        out.write('\n')

    out.write(')\n')

    if diststyle:
        out.write('DISTSTYLE {}\n'.format(diststyle))

    if distkey:
        out.write('DISTKEY({})\n'.format(distkey))

    if sortkey:
        if isinstance(sortkey, str):
            out.write('SORTKEY({})\n'.format(sortkey))
        elif len(sortkey) == 1:
            out.write('SORTKEY({})\n'.format(sortkey[0]))
        else:
            out.write('COMPOUND SORTKEY({})\n'.format(', '.join(sortkey)))

    return out.getvalue()