#!/usr/bin/env node
// MCP (Model Context Protocol) server for Signals & Subtractions.
// Zero dependencies, stdio transport, read-only. Pattern from every-ai-law
// scripts/mcp-server.js, trimmed: no tiers, no keys, no rate limiting.
//
// Dual data mode. Inside a repo clone it reads the same pre-generated JSON the
// public site serves at /api/v1/ (built by build-site.mjs into docs/api/v1/)
// plus the generated transcript pages; rebuild with `node scripts/build.mjs`
// to refresh what it sees. Outside a clone: this file is published at
// https://sigsub.show/mcp-server.mjs so anyone can download and run it: it
// fetches the live API and transcript pages instead. Either way a long-lived
// process re-reads its source after DATA_TTL_MS on its own.
//
// Usage:  node mcp-server.mjs
// Register (Claude Code): claude mcp add sigsub -- node /path/to/mcp-server.mjs
'use strict';

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const DATA_DIR = path.join(ROOT, 'docs', 'api', 'v1');
const SITE_FACTS_PATH = path.join(ROOT, 'site', 'site-facts.json');
const SITE = 'https://sigsub.show/';
const HTML_ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', '#39': "'", middot: '·' };
// Both markers must exist: a copy downloaded into the wrong parent directory
// could otherwise find a stray docs/api/v1 and silently read the wrong data.
const LOCAL_MODE = fs.existsSync(DATA_DIR) && fs.existsSync(SITE_FACTS_PATH);

export const SERVER_INFO = { name: 'signals-subtractions', version: '0.4.0' };
const SUPPORTED_PROTOCOL_VERSIONS = ['2026-07-28', '2024-11-05'];
const LEGACY_PROTOCOL_VERSION = '2024-11-05';
const PROTOCOL_VERSION_META_KEY = 'io.modelcontextprotocol/protocolVersion';
const DATA_TTL_MS = 3600000;
const FETCH_UA = `${SERVER_INFO.name}-mcp/${SERVER_INFO.version} (+${SITE})`;

async function fetchText(url) {
    const res = await fetch(url, {
        headers: { 'user-agent': FETCH_UA, accept: '*/*' },
        signal: AbortSignal.timeout(15000)
    });
    if (!res.ok) throw new Error(`GET ${url} -> HTTP ${res.status}`);
    return res.text();
}

async function loadData() {
    const loaded = {};
    if (LOCAL_MODE) {
        for (const file of fs.readdirSync(DATA_DIR).filter(f => f.endsWith('.json'))) {
            loaded[file.replace('.json', '')] = JSON.parse(fs.readFileSync(path.join(DATA_DIR, file), 'utf8'));
        }
        return loaded;
    }
    const names = ['index', 'episodes', 'pairs', 'takeaways', 'situations'];
    const bodies = await Promise.all(names.map(name => fetchText(`${SITE}api/v1/${name}.json`)));
    names.forEach((name, i) => { loaded[name] = JSON.parse(bodies[i]); });
    return loaded;
}

let data = {};
let dataLoadedAt = 0;

async function ensureData() {
    if (Object.keys(data).length > 0 && Date.now() - dataLoadedAt < DATA_TTL_MS) return;
    data = await loadData();
    dataLoadedAt = Date.now();
}

function dataUnavailableError(err) {
    return structuredError({
        error: 'data_unavailable',
        detail: `Could not load show data: ${err.message}`,
        why: LOCAL_MODE
            ? 'Local mode reads docs/api/v1/ from the repo clone; the generated files may be missing or corrupt.'
            : `Remote mode fetches ${SITE}api/v1/; the network or the site may be unreachable.`,
        guidance: LOCAL_MODE
            ? { fix: 'Run `node scripts/build.mjs` in the repo, then retry.' }
            : { fix: 'Check connectivity and retry.', api: `${SITE}api/v1/index.json` }
    });
}

function meta() {
    const m = data.index?.meta || {};
    return {
        generated: m.generated || null,
        server: `${SERVER_INFO.name}/${SERVER_INFO.version}`,
        data_source: LOCAL_MODE ? 'local repo clone' : SITE,
        rights: m.rights || 'All Rights Reserved',
        copyright_holder: m.copyright_holder || 'Snap Synapse LLC',
        rights_statement: m.rights_statement || 'Public discovery access does not grant redistribution rights.'
    };
}

function textResult(obj) {
    return { content: [{ type: 'text', text: JSON.stringify(obj, null, 2) }] };
}

function structuredError({ error, detail, why, guidance }) {
    return {
        content: [{ type: 'text', text: JSON.stringify({ error, detail, why, guidance }, null, 2) }],
        isError: true
    };
}

function invalidInputError(detail, guidance = {}) {
    return structuredError({
        error: 'invalid_input',
        detail,
        why: 'Tool arguments must match the advertised input schema before a handler runs.',
        guidance
    });
}

function validateSchemaValue(value, schema, pathName) {
    if (!schema || !schema.type) return null;
    if (schema.type === 'string') return typeof value === 'string' ? null : `${pathName} must be a string.`;
    if (schema.type === 'number') return typeof value === 'number' && Number.isFinite(value) ? null : `${pathName} must be a finite number.`;
    if (schema.type === 'object') {
        if (!value || typeof value !== 'object' || Array.isArray(value)) return `${pathName} must be an object.`;
        return null;
    }
    return null;
}

function validateToolArguments(tool, args) {
    const schema = tool.inputSchema || {};
    const normalized = args;
    const objectError = validateSchemaValue(normalized, schema, 'arguments');
    if (objectError) return invalidInputError(objectError);

    const properties = schema.properties || {};
    for (const key of schema.required || []) {
        if (!Object.prototype.hasOwnProperty.call(normalized, key)) {
            return invalidInputError(`Missing required argument: ${key}.`, { required: schema.required });
        }
    }
    if (schema.additionalProperties === false) {
        const allowed = new Set(Object.keys(properties));
        const extra = Object.keys(normalized).filter(key => !allowed.has(key));
        if (extra.length > 0) {
            return invalidInputError(`Unexpected argument(s): ${extra.join(', ')}.`, { allowed_arguments: [...allowed] });
        }
    }
    for (const [key, propertySchema] of Object.entries(properties)) {
        if (!Object.prototype.hasOwnProperty.call(normalized, key)) continue;
        const valueError = validateSchemaValue(normalized[key], propertySchema, key);
        if (valueError) return invalidInputError(valueError);
    }
    return null;
}

function episodes() {
    return data.episodes?.episodes || [];
}

function findEpisode(number) {
    return episodes().find(ep => ep.episodeNumber === number);
}

function episodeNotFound(number) {
    const known = episodes().map(ep => ep.episodeNumber);
    return structuredError({
        error: 'not_found',
        detail: `No shipped episode numbered ${number}.`,
        why: 'Only shipped episodes are published to the API; in-production episodes are not visible here.',
        guidance: { use_tool: 'list_episodes', shipped_episodes: known }
    });
}

// Tool definitions
export const TOOLS = [
    {
        name: 'list_episodes',
        description: 'List every shipped episode of Signals & Subtractions: number, title, date, duration, cast, and platform URLs.',
        inputSchema: { type: 'object', properties: {}, additionalProperties: false }
    },
    {
        name: 'get_episode',
        description: 'Get the full record for one episode by number: cast, lede, signals, subtractions, and every platform URL.',
        inputSchema: {
            type: 'object',
            properties: { episode: { type: 'number', description: 'Episode number (e.g. 1, 6)' } },
            required: ['episode'], additionalProperties: false
        }
    },
    {
        name: 'get_transcript',
        description: 'Get the full transcript of an episode as plain text, one timestamped speaker turn per line.',
        inputSchema: {
            type: 'object',
            properties: { episode: { type: 'number', description: 'Episode number (e.g. 1, 6)' } },
            required: ['episode'], additionalProperties: false
        }
    },
    {
        name: 'search_pairs',
        description: 'Search every signal + subtraction pair the newsletter has published (one continuous issue counter from 001) by keyword. An empty query lists all pairs.',
        inputSchema: {
            type: 'object',
            properties: { query: { type: 'string', description: 'Keyword to match against issue title, signal, and subtraction. Empty string returns every pair.' } },
            required: ['query'], additionalProperties: false
        }
    },
    {
        name: 'search_transcripts',
        description: 'Search every timestamped speaker turn of every published episode transcript by keyword. Each match carries the episode, speaker, timestamp, transcript URL, and a video URL that jumps to the moment.',
        inputSchema: {
            type: 'object',
            properties: {
                query: { type: 'string', description: 'Keyword to match against transcript text (case-insensitive substring).' },
                episode: { type: 'number', description: 'Optional: restrict the search to one episode number.' }
            },
            required: ['query'], additionalProperties: false
        }
    },
    {
        name: 'list_takeaways',
        description: 'List every published takeaway of Signals & Subtractions: a one-page method with a JSON schema and a copy-paste prompt. Returns slug, title, method, shape, stage, page URL, and the episode it shipped with.',
        inputSchema: { type: 'object', properties: {}, additionalProperties: false }
    },
    {
        name: 'get_takeaway',
        description: 'Get one takeaway by slug: its page fields plus the parsed JSON schema and the copy-paste prompt, verbatim, ready to run with any model.',
        inputSchema: {
            type: 'object',
            properties: { slug: { type: 'string', description: 'Takeaway slug, the last path segment of its page URL (e.g. pilot-kill-card). list_takeaways gives every slug.' } },
            required: ['slug'], additionalProperties: false
        }
    },
    {
        name: 'list_situations',
        description: 'List every situation: a problem in the words people use for it (for example, the supplier changed the model after sign-off), with a short answer and the published takeaways to run in order. Each takeaway carries its page URL; get_takeaway gives its schema and prompt.',
        inputSchema: { type: 'object', properties: {}, additionalProperties: false }
    }
];

// Tool handlers
function handleListEpisodes() {
    const list = episodes().map(ep => ({
        episode: ep.episodeNumber,
        name: ep.name,
        datePublished: ep.datePublished,
        duration: ep.duration,
        host: ep.host,
        ...(ep.cohost ? { cohost: ep.cohost } : {}),
        ...(ep.guest ? { guest: ep.guest } : {}),
        url: ep.url,
        video: ep.video,
        transcript: ep.transcript
    }));
    return textResult({ meta: meta(), data: list, count: list.length });
}

function handleGetEpisode({ episode }) {
    const ep = findEpisode(episode);
    if (!ep) return episodeNotFound(episode);
    return textResult({ meta: meta(), data: ep });
}

// Transcript pages are generated HTML with one .cue block per speaker turn:
// a stamp link (m:ss into the video), a <strong> speaker, then paragraphs.
function parseTranscriptHtml(html) {
    const lines = [];
    for (const [, cue] of html.matchAll(/<div class="cue"(?:\s+id="[^"]+")?>([\s\S]*?)<\/div>/g)) {
        const stamp = cue.match(/class="stamp"[^>]*>([^<]+)</)?.[1] || '';
        const who = cue.match(/<strong>([^<]+)<\/strong>/)?.[1] || '';
        const text = [...cue.matchAll(/<p>([\s\S]*?)<\/p>/g)]
            .map(m => m[1])
            .join(' ')
            .replace(/<[^>]+>/g, '')
            // One pass, so an escaped entity such as &amp;lt; decodes to &lt; and not to <.
            .replace(/&(amp|lt|gt|quot|#39|middot);/g, (_, name) => HTML_ENTITIES[name])
            .replace(/\s+/g, ' ')
            .trim();
        if (text) lines.push(`[${stamp}] ${who}: ${text}`);
    }
    return lines;
}

async function handleGetTranscript({ episode }) {
    const ep = findEpisode(episode);
    if (!ep) return episodeNotFound(episode);
    if (!ep.transcript) {
        return structuredError({
            error: 'not_found',
            detail: `Episode ${episode} has no published transcript.`,
            why: 'Transcripts are generated per episode; this one has not been built or published yet.',
            guidance: { episode_page: ep.url, video: ep.video }
        });
    }

    let html;
    if (LOCAL_MODE) {
        const rel = path.join('episodes', `ep-${String(episode).padStart(3, '0')}`, 'transcript', 'index.html');
        const file = path.join(ROOT, 'docs', rel);
        if (!fs.existsSync(file)) {
            return structuredError({
                error: 'not_found',
                detail: `Episode ${episode} has no transcript page at docs/${rel}.`,
                why: 'Transcripts are generated per episode; this one has not been built or published yet.',
                guidance: { episode_page: ep.url, video: ep.video }
            });
        }
        html = fs.readFileSync(file, 'utf8');
    } else {
        try {
            html = await fetchText(ep.transcript);
        } catch (err) {
            return structuredError({
                error: 'fetch_failed',
                detail: `Could not fetch the transcript page: ${err.message}`,
                why: 'Remote mode reads transcripts from the live site.',
                guidance: { transcript_url: ep.transcript, retry: true }
            });
        }
    }

    const lines = parseTranscriptHtml(html);
    if (lines.length === 0) {
        return structuredError({
            error: 'tool_error',
            detail: `Transcript page for episode ${episode} exists but no speaker turns were parsed.`,
            why: 'The transcript page markup may have changed shape; the parser expects .cue blocks.',
            guidance: { transcript_url: ep.transcript }
        });
    }
    return textResult({
        meta: meta(),
        data: {
            episode: ep.episodeNumber,
            name: ep.name,
            transcript_url: ep.transcript,
            note: 'Lightly machine-transcribed, may contain errors. Timestamps are minutes:seconds into the video.',
            turns: lines
        }
    });
}

function handleSearchPairs({ query }) {
    const q = query.trim().toLowerCase();
    const pairs = data.pairs?.pairs || [];
    const results = [];
    for (const pair of pairs) {
        if (!q) { results.push({ ...pair, score: 0 }); continue; }
        let score = 0;
        if (pair.title?.toLowerCase().includes(q)) score = Math.max(score, 80);
        if (pair.signal?.toLowerCase().includes(q)) score = Math.max(score, 60);
        if (pair.subtraction?.toLowerCase().includes(q)) score = Math.max(score, 60);
        if (score > 0) results.push({ ...pair, score });
    }
    if (q) results.sort((a, b) => b.score - a.score || a.issue - b.issue);
    return textResult({
        meta: meta(),
        data: results,
        total_matches: results.length,
        ...(q ? {} : { note: 'Empty query: every published pair, oldest first.' })
    });
}

// The transcript index is the one heavy file (hundreds of KB), so remote mode
// fetches it on first use rather than at every data load; local mode already
// has it, because loadData() reads every JSON in docs/api/v1/.
async function handleSearchTranscripts({ query, episode }) {
    if (!data['search-transcripts']) {
        try {
            data['search-transcripts'] = JSON.parse(await fetchText(`${SITE}api/v1/search-transcripts.json`));
        } catch (err) {
            return dataUnavailableError(err);
        }
    }
    const q = String(query || '').trim().toLowerCase();
    if (!q) {
        return structuredError({
            error: 'empty_query',
            detail: 'search_transcripts needs a keyword; an empty query would return every turn of every transcript.',
            guidance: { fix: 'Pass a search term, or use get_transcript for one full episode.' }
        });
    }
    const results = [];
    for (const ep of data['search-transcripts'].episodes || []) {
        if (episode !== undefined && ep.episode !== episode) continue;
        for (const [index, [secs, speaker, text]] of ep.turns.entries()) {
            if (!text.toLowerCase().includes(q)) continue;
            results.push({
                episode: ep.episode, title: ep.title, speaker,
                seconds: secs, text,
                transcript: `${ep.transcript}#${ep.anchors?.[index] || `t-${secs}`}`,
                ...(ep.video ? { video_at: `${ep.video}${ep.video.includes('?') ? '&' : '?'}t=${secs}` } : {})
            });
        }
    }
    return textResult({ meta: meta(), data: results, total_matches: results.length });
}

// Takeaways: docs/api/v1/takeaways.json is a plain array, one entry per
// published page, with the schema already parsed and the prompt verbatim.
function takeaways() {
    return Array.isArray(data.takeaways) ? data.takeaways : [];
}

function handleListTakeaways() {
    const list = takeaways().map(tk => ({
        slug: tk.slug,
        title: tk.title,
        method: tk.method,
        shape: tk.shape,
        stage: tk.stage,
        url: tk.url,
        ...(tk.episode ? { episode: tk.episode } : {}),
        has_schema: tk.schema !== null,
        updated: tk.updated
    }));
    return textResult({ meta: meta(), data: list, count: list.length });
}

function handleGetTakeaway({ slug }) {
    const key = String(slug || '').trim().toLowerCase().replace(/^\/?takeaways\//, '').replace(/\/$/, '');
    const tk = takeaways().find(t => t.slug === key);
    if (!tk) {
        return structuredError({
            error: 'not_found',
            detail: `No published takeaway with slug "${slug}".`,
            why: 'Only takeaways whose own draft state is false are in the API; drafts and previews are not visible here, and episode release is not required.',
            guidance: { use_tool: 'list_takeaways', published_slugs: takeaways().map(t => t.slug) }
        });
    }
    return textResult({ meta: meta(), data: tk });
}

// Situations: docs/api/v1/situations.json is a plain array, one entry per
// situation, each naming the takeaways that answer it in order.
function situations() {
    return Array.isArray(data.situations) ? data.situations : [];
}

function handleListSituations() {
    const list = situations();
    return textResult({ meta: meta(), data: list, count: list.length });
}

const TOOL_HANDLERS = {
    list_episodes: handleListEpisodes,
    get_episode: handleGetEpisode,
    get_transcript: handleGetTranscript,
    search_pairs: handleSearchPairs,
    search_transcripts: handleSearchTranscripts,
    list_takeaways: handleListTakeaways,
    get_takeaway: handleGetTakeaway,
    list_situations: handleListSituations
};

const TOOL_BY_NAME = new Map(TOOLS.map(tool => [tool.name, tool]));

// JSON-RPC transport
function jsonRpcResponse(id, result) {
    return JSON.stringify({ jsonrpc: '2.0', id, result: { resultType: 'complete', ...result } });
}

function jsonRpcError(id, code, message, extra) {
    return JSON.stringify({ jsonrpc: '2.0', id, error: { code, message, ...(extra ? { data: extra } : {}) } });
}

export async function handleMessage(msg) {
    const responseId = msg && typeof msg === 'object'
        && (typeof msg.id === 'string' || (typeof msg.id === 'number' && Number.isFinite(msg.id))) ? msg.id : null;
    if (!msg || typeof msg !== 'object' || Array.isArray(msg) || msg.jsonrpc !== '2.0'
        || typeof msg.method !== 'string'
        || (msg.id !== undefined && msg.id !== null && responseId === null)) {
        return jsonRpcError(responseId, -32600, 'Invalid Request');
    }
    const { id, method, params } = msg;
    if (params !== undefined && (!params || typeof params !== 'object' || Array.isArray(params))) {
        return jsonRpcError(id ?? null, -32602, 'Parameters must be an object');
    }

    const requestedVersion = params?._meta?.[PROTOCOL_VERSION_META_KEY];
    if (id !== undefined && requestedVersion !== undefined && !SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion)) {
        return jsonRpcError(id, -32022, 'Unsupported protocol version', {
            supported: SUPPORTED_PROTOCOL_VERSIONS,
            requested: requestedVersion
        });
    }

    switch (method) {
        case 'initialize':
            return jsonRpcResponse(id, {
                protocolVersion: SUPPORTED_PROTOCOL_VERSIONS.includes(params?.protocolVersion)
                    ? params.protocolVersion
                    : LEGACY_PROTOCOL_VERSION,
                capabilities: { tools: {} },
                serverInfo: SERVER_INFO
            });
        case 'notifications/initialized':
            return null;
        case 'ping':
            return jsonRpcResponse(id, {});
        case 'server/discover':
            return jsonRpcResponse(id, {
                supportedVersions: SUPPORTED_PROTOCOL_VERSIONS,
                capabilities: { tools: {} },
                _meta: { 'io.modelcontextprotocol/serverInfo': SERVER_INFO },
                ttlMs: DATA_TTL_MS,
                cacheScope: 'public'
            });
        case 'tools/list':
            return jsonRpcResponse(id, { tools: TOOLS, ttlMs: DATA_TTL_MS, cacheScope: 'public' });
        case 'tools/call': {
            const toolName = params?.name;
            if (typeof toolName !== 'string') return jsonRpcError(id ?? null, -32602, 'Tool name must be a string');
            const handler = typeof toolName === 'string' && Object.hasOwn(TOOL_HANDLERS, toolName) ? TOOL_HANDLERS[toolName] : null;
            if (!handler) {
                return jsonRpcResponse(id, structuredError({
                    error: 'unknown_tool',
                    detail: `No tool named "${toolName}".`,
                    why: 'The tool name must match one of the registered MCP tools exactly.',
                    guidance: { available_tools: Object.keys(TOOL_HANDLERS) }
                }));
            }
            const argumentsValue = params?.arguments === undefined ? {} : params.arguments;
            const validationError = validateToolArguments(TOOL_BY_NAME.get(toolName), argumentsValue);
            if (validationError) return jsonRpcResponse(id, validationError);
            try {
                await ensureData();
            } catch (err) {
                return jsonRpcResponse(id, dataUnavailableError(err));
            }
            try {
                return jsonRpcResponse(id, await handler(argumentsValue));
            } catch (err) {
                return jsonRpcResponse(id, structuredError({
                    error: 'tool_error',
                    detail: `Tool "${toolName}" threw an error: ${err.message}`,
                    why: 'An unexpected error occurred.',
                    guidance: { retry: true }
                }));
            }
        }
        default:
            if (method?.startsWith('notifications/')) return null;
            return jsonRpcError(id, -32601, `Method not found: ${method}`);
    }
}

function startStdioServer() {
    let buffer = '';
    let processing = Promise.resolve();

    process.stdin.setEncoding('utf8');
    process.stdin.on('data', chunk => {
        buffer += chunk;
        let newlineIdx;
        while ((newlineIdx = buffer.indexOf('\n')) !== -1) {
            const line = buffer.slice(0, newlineIdx).trim();
            buffer = buffer.slice(newlineIdx + 1);
            if (!line) continue;
            let msg;
            try {
                msg = JSON.parse(line);
            } catch {
                process.stdout.write(jsonRpcError(null, -32700, 'Parse error') + '\n');
                continue;
            }
            processing = processing.then(async () => {
                const response = await handleMessage(msg);
                if (response !== null) process.stdout.write(response + '\n');
            }).catch(() => {
                const id = msg && (typeof msg.id === 'string' || typeof msg.id === 'number') ? msg.id : null;
                process.stdout.write(jsonRpcError(id, -32603, 'Internal error') + '\n');
            });
        }
    });
    process.stdin.on('end', () => {
        processing.finally(() => process.exit(0));
    });
    process.on('uncaughtException', err => {
        console.error('[mcp-server] Uncaught exception:', err.message);
    });
    ensureData().then(() => {
        console.error(`[mcp-server] Signals & Subtractions MCP server started (${LOCAL_MODE ? 'local' : 'remote'} data from ${LOCAL_MODE ? 'repo clone' : SITE}, ${data.index?.meta?.generated || 'unknown'}, ${episodes().length} episodes)`);
    }).catch(err => {
        console.error(`[mcp-server] started in ${LOCAL_MODE ? 'local' : 'remote'} mode but initial data load failed (${err.message}); will retry per call`);
    });
}

if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
    startStdioServer();
}
