-- Add params_schema to functions: JSON with semantic descriptions of inputs/outputs.
-- Format: {"params":[{"name":"x","desc":"..."}],"output":"..."}
-- Enables agent reasoning about function composability.

ALTER TABLE functions ADD COLUMN params_schema TEXT NOT NULL DEFAULT '';

-- Rebuild FTS for functions: add params_schema
DROP TRIGGER IF EXISTS functions_ai;
DROP TRIGGER IF EXISTS functions_ad;
DROP TRIGGER IF EXISTS functions_au;

INSERT INTO functions_fts(functions_fts) VALUES('rebuild');
DROP TABLE IF EXISTS functions_fts;

CREATE VIRTUAL TABLE functions_fts USING fts5(
    id,
    name,
    description,
    tags,
    signature,
    domain,
    example,
    notes,
    documentation,
    code,
    params_schema,
    content='functions',
    content_rowid='rowid'
);

-- Populate FTS from existing data
INSERT INTO functions_fts(rowid, id, name, description, tags, signature, domain, example, notes, documentation, code, params_schema)
SELECT rowid, id, name, description, tags, signature, domain, example, notes, documentation, code, params_schema
FROM functions;

CREATE TRIGGER functions_ai AFTER INSERT ON functions BEGIN
    INSERT INTO functions_fts(rowid, id, name, description, tags, signature, domain, example, notes, documentation, code, params_schema)
    VALUES (new.rowid, new.id, new.name, new.description, new.tags, new.signature, new.domain, new.example, new.notes, new.documentation, new.code, new.params_schema);
END;

CREATE TRIGGER functions_ad AFTER DELETE ON functions BEGIN
    INSERT INTO functions_fts(functions_fts, rowid, id, name, description, tags, signature, domain, example, notes, documentation, code, params_schema)
    VALUES ('delete', old.rowid, old.id, old.name, old.description, old.tags, old.signature, old.domain, old.example, old.notes, old.documentation, old.code, old.params_schema);
END;

CREATE TRIGGER functions_au AFTER UPDATE ON functions BEGIN
    INSERT INTO functions_fts(functions_fts, rowid, id, name, description, tags, signature, domain, example, notes, documentation, code, params_schema)
    VALUES ('delete', old.rowid, old.id, old.name, old.description, old.tags, old.signature, old.domain, old.example, old.notes, old.documentation, old.code, old.params_schema);
    INSERT INTO functions_fts(rowid, id, name, description, tags, signature, domain, example, notes, documentation, code, params_schema)
    VALUES (new.rowid, new.id, new.name, new.description, new.tags, new.signature, new.domain, new.example, new.notes, new.documentation, new.code, new.params_schema);
END;
