"""Pure insertion helpers; import is inert. Future builder owns the fresh DB."""
from gnd_adapter import need, project

def next_source_rank(db):
    # One query per scope, not per row. A later source cannot replace an old
    # display spelling, even for prior records that have no training base_json.
    value = db.execute('SELECT COALESCE(MAX(priority),-1) FROM names').fetchone()[0]
    need(type(value) is int and value >= -1, 'Unexpected baseline display priority')
    return value + 1

def merge_authority_row(catalog, row, policy, rank):
    need(type(rank) is int and rank >= 0, 'A frozen later-source rank is required')
    events = list(project(row, policy))
    # Catalog.event's form argument also chooses the display name for a fresh
    # key. Pass the source representative; insert ALL literal forms explicitly.
    for event in events:
        catalog.event(row['key'], row['form'], event, rank)
    for literal in row['forms']:
        catalog.db.execute('INSERT OR IGNORE INTO forms VALUES(?,?)', (row['key'], literal))
    return {'source_role_rows': 1, 'source_literal_relation_events': len(events)}
