UNPKG

@withpica/mcp-server

Version:

MCP Server for withPICA — enables AI assistants to interact with your withPICA music catalog

969 lines • 51.7 kB
// Copyright (c) 2025-2026 Withpica Ltd. All rights reserved.
import { webBaseUrl } from "../lib/view-url.js";
import { formatList, formatSuccess, formatValidationError, } from "@withpica/mcp-utils";
export class MultimediaTools {
    pica;
    constructor(pica) {
        this.pica = pica;
    }
    getTools() {
        return [
            {
                definition: {
                    name: "pica_multimedia_search",
                    scope: "read:files",
                    audiences: ["stdio", "http", "public"],
                    tier: "read",
                    description: "Search and list multimedia assets — photos, videos, audio, YouTube, Spotify, SoundCloud. " +
                        "Supports filtering by type, classification, published status, and linked work or person. " +
                        "Read-only: to add an item rather than find one, use pica_multimedia_create.",
                    workflows: "infrastructure",
                    vernacular_kind: "specialist",
                    vernacular_reason: "Specialist context; not yet covered by the Creator Question Atlas — pending telemetry-driven addition per ADR-226 Phase 4 substrate writes.",
                    inputSchema: {
                        type: "object",
                        properties: {
                            query: {
                                type: "string",
                                description: "Full-text search across title, caption, and description",
                            },
                            content_type: {
                                type: "string",
                                description: "Filter by content type",
                                enum: [
                                    "uploaded_photo",
                                    "uploaded_video",
                                    "uploaded_audio",
                                    "youtube_video",
                                    "spotify_track",
                                    "soundcloud_track",
                                    "live_performance",
                                ],
                            },
                            classification: {
                                type: "string",
                                description: "Filter by classification",
                                enum: [
                                    "sync_placement",
                                    "music_video",
                                    "behind_the_scenes",
                                    "live_performance",
                                    "promo_material",
                                    "album_artwork",
                                    "studio_session",
                                    "artist_showcase",
                                    "general",
                                ],
                            },
                            is_published: {
                                type: "boolean",
                                description: "Filter by published status",
                            },
                            work_id: {
                                type: "string",
                                description: "Filter by linked work ID",
                            },
                            person_id: {
                                type: "string",
                                description: "Filter by linked person ID",
                            },
                            limit: {
                                type: "number",
                                minimum: 1,
                                maximum: 200,
                                description: "Maximum results (default: 50, max: 200)",
                            },
                            offset: {
                                type: "number",
                                description: "Pagination offset (default: 0)",
                            },
                        },
                    },
                },
                executor: this.searchMultimedia.bind(this),
            },
            {
                definition: {
                    name: "pica_multimedia_inspect",
                    scope: "read:files",
                    audiences: ["stdio", "http", "public"],
                    tier: "read",
                    description: "Get one photo, video or other media item in this catalogue by id. " +
                        "Read-only. To find items by title, type or linked work, use pica_multimedia_search.",
                    workflows: "infrastructure",
                    vernacular_kind: "specialist",
                    vernacular_reason: "Specialist context; not yet covered by the Creator Question Atlas — pending telemetry-driven addition per ADR-226 Phase 4 substrate writes.",
                    // id/multimedia_id are interchangeable — the write tools
                    // (pica_multimedia_link_work) name it multimedia_id. Same pattern as
                    // pica_notes_inspect.
                    requiredOneOf: [["id", "multimedia_id"]],
                    inputSchema: {
                        type: "object",
                        properties: {
                            id: { type: "string", description: "Media item ID" },
                            multimedia_id: {
                                type: "string",
                                description: "Media item ID (alias for id — write tools use multimedia_id).",
                            },
                        },
                        required: [],
                    },
                },
                executor: this.inspectMultimedia.bind(this),
            },
            {
                definition: {
                    name: "pica_multimedia_create",
                    scope: "write:files",
                    audiences: ["stdio", "http", "public"],
                    tier: "write",
                    description: "Create a multimedia item. Use for linking external content " +
                        "(YouTube, Spotify, SoundCloud URLs) or registering uploaded media. " +
                        "For actual file uploads use pica_upload (interactive) or pica_upload_file + " +
                        "pica_upload_complete; for YouTube videos with auto-enriched metadata use " +
                        "pica_multimedia_link_youtube.",
                    workflows: ["multimedia-required"],
                    vernacular_kind: "specialist",
                    vernacular_reason: "Specialist context; not yet covered by the Creator Question Atlas — pending telemetry-driven addition per ADR-226 Phase 4 substrate writes.",
                    inputSchema: {
                        type: "object",
                        properties: {
                            title: {
                                type: "string",
                                description: "Title of the multimedia item.",
                            },
                            content_type: {
                                type: "string",
                                description: "Type of content.",
                                enum: [
                                    "uploaded_photo",
                                    "uploaded_video",
                                    "uploaded_audio",
                                    "youtube_video",
                                    "spotify_track",
                                    "soundcloud_track",
                                    "live_performance",
                                ],
                            },
                            url: {
                                type: "string",
                                description: "URL of the media (YouTube URL, Spotify URI, SoundCloud URL, etc.).",
                            },
                            classification: {
                                type: "string",
                                description: "Classification of the content.",
                                enum: [
                                    "sync_placement",
                                    "music_video",
                                    "behind_the_scenes",
                                    "live_performance",
                                    "promo_material",
                                    "album_artwork",
                                    "studio_session",
                                    "artist_showcase",
                                    "general",
                                ],
                            },
                            caption: { type: "string", description: "Caption or subtitle." },
                            description: {
                                type: "string",
                                description: "Detailed description.",
                            },
                            tags: {
                                type: "array",
                                description: "Tags for categorisation.",
                                items: { type: "string" },
                            },
                            credits: {
                                type: "string",
                                description: "Freeform credits string (e.g. 'Shot by Alice Nguyen, produced by Bob').",
                            },
                            duration_seconds: {
                                type: "number",
                                description: "Duration in seconds (for video / audio).",
                            },
                            // Collection / ordering / publish
                            collection_id: {
                                type: "string",
                                description: "Collection UUID — attach this item to a multimedia collection.",
                            },
                            display_order: {
                                type: "number",
                                description: "Sort position within its collection.",
                            },
                            is_featured: {
                                type: "boolean",
                                description: "Mark as featured — surfaces in prominent positions on artist portals and directory.",
                            },
                            is_published: {
                                type: "boolean",
                                description: "Publish to public surfaces on create. Default false; the service stamps `published_at` when this flips true.",
                            },
                            // Event / performance context (audit row 21 add-candidates)
                            venue: {
                                type: "string",
                                description: "Venue name (for live / performance content).",
                            },
                            event_name: {
                                type: "string",
                                description: "Event / tour / show name (for live / performance content).",
                            },
                            performance_date: {
                                type: "string",
                                description: "Date of the performance (YYYY-MM-DD) — used to timestamp live recordings.",
                            },
                            setlist_position: {
                                type: "number",
                                description: "Work's position in the performance setlist (1-indexed).",
                            },
                            sync_side: {
                                type: "string",
                                description: "Sync-side label for sync placements (e.g. 'master', 'publishing').",
                            },
                            // External identifiers (enrichment pipelines may overwrite)
                            spotify_url: {
                                type: "string",
                                description: "Spotify canonical URL.",
                            },
                            spotify_track_uri: {
                                type: "string",
                                description: "Spotify URI (spotify:track:…).",
                            },
                            spotify_track_id: {
                                type: "string",
                                description: "Spotify track ID (22 chars).",
                            },
                            youtube_url: {
                                type: "string",
                                description: "YouTube canonical URL.",
                            },
                            youtube_video_id: {
                                type: "string",
                                description: "YouTube video ID (e.g. 'dQw4w9WgXcQ').",
                            },
                            soundcloud_url: {
                                type: "string",
                                description: "SoundCloud canonical URL.",
                            },
                            thumbnail_url: {
                                type: "string",
                                description: "Externally-hosted thumbnail URL.",
                            },
                        },
                        required: ["title", "content_type"],
                    },
                },
                executor: this.createMultimedia.bind(this),
            },
            {
                definition: {
                    name: "pica_multimedia_import_url",
                    scope: "write:files",
                    audiences: ["stdio", "http", "public"],
                    tier: "write",
                    // Open world: fetches the image (or its page) from the URL given.
                    annotations: { openWorldHint: true },
                    description: "Import an image or video from a public URL — downloads it and stores it in PICA. " +
                        "Works with direct image links AND web pages that declare a preview image (og:image), " +
                        "e.g. postimg, imgur, press pages. Pass person_id to set the imported image as that " +
                        "person's profile image (artist photo, avatar, press photo, profile picture) in the " +
                        "same call. For YouTube videos, use pica_multimedia_link_youtube instead.",
                    workflows: ["multimedia-required"],
                    vernacular_kind: "specialist",
                    vernacular_reason: "Specialist context; not yet covered by the Creator Question Atlas — pending telemetry-driven addition per ADR-226 Phase 4 substrate writes.",
                    inputSchema: {
                        type: "object",
                        properties: {
                            url: {
                                type: "string",
                                description: "Public URL of the image or video to import",
                            },
                            title: {
                                type: "string",
                                description: "Title for the multimedia item",
                            },
                            source: {
                                type: "string",
                                description: "Source label (e.g. 'spotify', 'web', 'press_kit')",
                            },
                            work_id: {
                                type: "string",
                                description: "Optional work ID to link the imported media to",
                            },
                            person_id: {
                                type: "string",
                                description: "Optional person id — set the imported image as this person's profile image (artist photo / avatar). The person must belong to your organisation.",
                            },
                        },
                        required: ["url"],
                    },
                },
                executor: this.importFromUrl.bind(this),
            },
            {
                definition: {
                    name: "pica_multimedia_link_youtube",
                    scope: "write:files",
                    audiences: ["stdio", "http", "public"],
                    tier: "write",
                    description: "Link a YouTube video to PICA. Creates a multimedia item with YouTube metadata " +
                        "(thumbnail, title, view count). Can optionally link to a work. " +
                        "For any other image or video URL, use pica_multimedia_import_url instead.",
                    workflows: ["multimedia-required"],
                    vernacular_kind: "specialist",
                    vernacular_reason: "Specialist context; not yet covered by the Creator Question Atlas — pending telemetry-driven addition per ADR-226 Phase 4 substrate writes.",
                    inputSchema: {
                        type: "object",
                        properties: {
                            youtube_video_id: {
                                type: "string",
                                description: "YouTube video ID (e.g. 'dQw4w9WgXcQ' from youtube.com/watch?v=dQw4w9WgXcQ)",
                            },
                            title: {
                                type: "string",
                                description: "Title for the multimedia item",
                            },
                            classification: {
                                type: "string",
                                description: "Classification type",
                                enum: [
                                    "sync_placement",
                                    "music_video",
                                    "behind_the_scenes",
                                    "live_performance",
                                    "promo_material",
                                    "general",
                                ],
                            },
                            work_id: {
                                type: "string",
                                description: "Optional work ID to link the video to",
                            },
                            work_relationship_type: {
                                type: "string",
                                description: "Relationship type when linking to a work (e.g. 'music_video_for', 'sync_placement')",
                            },
                        },
                        required: ["youtube_video_id", "title"],
                    },
                },
                executor: this.linkYoutube.bind(this),
            },
            {
                definition: {
                    name: "pica_multimedia_link_work",
                    scope: "write:files",
                    audiences: ["stdio", "http", "public"],
                    tier: "write",
                    description: "Link an existing multimedia item to a work. Creates a relationship between " +
                        "the multimedia (photo, video, audio) and a musical work. " +
                        "The item must already exist — create one first with pica_multimedia_create.",
                    workflows: ["multimedia-required"],
                    vernacular_kind: "specialist",
                    vernacular_reason: "Specialist context; not yet covered by the Creator Question Atlas — pending telemetry-driven addition per ADR-226 Phase 4 substrate writes.",
                    inputSchema: {
                        type: "object",
                        properties: {
                            multimedia_id: {
                                type: "string",
                                description: "The multimedia item ID",
                            },
                            work_id: {
                                type: "string",
                                description: "The work ID to link to",
                            },
                            relationship_type: {
                                type: "string",
                                description: "Type of relationship",
                                enum: [
                                    "featured_in",
                                    "music_video_for",
                                    "cover_performance",
                                    "album_artwork",
                                    "behind_the_scenes",
                                    "sync_placement",
                                    "general",
                                ],
                            },
                            notes: {
                                type: "string",
                                description: "Optional notes about the relationship",
                            },
                        },
                        required: ["multimedia_id", "work_id", "relationship_type"],
                    },
                },
                executor: this.linkWork.bind(this),
            },
            {
                definition: {
                    name: "pica_site_images_set",
                    scope: "write:files",
                    audiences: ["stdio", "http"],
                    tier: "write",
                    description: "Use when the user wants a photo on their public page: 'use this as my main photo', 'change my profile picture', 'take the photo off the top of my page'. " +
                        "Sets or removes the main photo (slot 'hero', across the top) or the profile picture (slot 'profile') from one of the catalogue's own uploaded photos; find one with pica_multimedia_search (content_type 'uploaded_photo'). photo_id null removes the pick. " +
                        "A photo that wasn't public is made public, so it also shows among the page's photos: say so to the user. The photo a pick replaces is never unpublished; it stays public: say so to the user, and offer to take it off with pica_site_images_take_off. " +
                        "Only after the user said which photo and which slot.",
                    workflows: "infrastructure",
                    vernacular_kind: "specialist",
                    vernacular_reason: "Specialist context; not yet covered by the Creator Question Atlas.",
                    inputSchema: {
                        type: "object",
                        properties: {
                            slot: {
                                type: "string",
                                enum: ["hero", "profile"],
                                description: "'hero' for the main photo across the top of the page, 'profile' for the profile picture.",
                            },
                            photo_id: {
                                type: ["string", "null"],
                                description: "The id of one of the catalogue's uploaded photos, or null to remove the pick.",
                            },
                        },
                        required: ["slot", "photo_id"],
                    },
                },
                executor: this.setSiteImage.bind(this),
            },
            {
                definition: {
                    name: "pica_site_images_take_off",
                    scope: "write:files",
                    audiences: ["stdio", "http"],
                    tier: "write",
                    description: "Use when the user wants one thing off their public page: 'take that photo off my page', 'hide this video from my site', 'I don't want that on my page'. " +
                        "Takes ONE photo, video, YouTube or Spotify item off the public page: it becomes private again and its public file is removed, and it stays in the catalogue. One named item per call; find it with pica_multimedia_search. " +
                        "The main photo and profile picture can't be taken off: replace or remove them first with pica_site_images_set. Only after the user said which item.",
                    workflows: "infrastructure",
                    vernacular_kind: "specialist",
                    vernacular_reason: "Specialist context; not yet covered by the Creator Question Atlas.",
                    inputSchema: {
                        type: "object",
                        properties: {
                            multimedia_id: {
                                type: "string",
                                description: "The id of the one item to take off the page.",
                            },
                        },
                        required: ["multimedia_id"],
                    },
                },
                executor: this.takeOffPage.bind(this),
            },
            {
                definition: {
                    name: "pica_site_images_put_back",
                    scope: "write:files",
                    audiences: ["stdio", "http"],
                    tier: "write",
                    description: "Use when the user wants something back on their public page that was taken off it: 'put that photo back on my page', 'undo, show it again'. " +
                        "Puts ONE item back on the public page. Only something taken off with pica_site_images_take_off (or the settings list) can be put back; it never makes public anything that wasn't. One named item per call. " +
                        "Only after the user said which item.",
                    workflows: "infrastructure",
                    vernacular_kind: "specialist",
                    vernacular_reason: "Specialist context; not yet covered by the Creator Question Atlas.",
                    inputSchema: {
                        type: "object",
                        properties: {
                            multimedia_id: {
                                type: "string",
                                description: "The id of the one item to put back on the page.",
                            },
                        },
                        required: ["multimedia_id"],
                    },
                },
                executor: this.putBackOnPage.bind(this),
            },
            {
                definition: {
                    name: "pica_site_sections_set",
                    scope: "write:files",
                    audiences: ["stdio", "http"],
                    tier: "write",
                    description: "Use when the user wants a whole part of their public page shown or hidden: 'hide the photos on my page', 'show my videos again', 'take the music section off my site'. " +
                        "Shows or hides ONE of three sections: 'photos', 'watch' (videos and YouTube) or 'listen' (tracks and audio). Hiding a section doesn't make anything private: photos, videos and Spotify tracks stay public at their own links (take one off for good with pica_site_images_take_off), and uploaded audio files simply stop being heard on the page. " +
                        "No other section can be switched. One section per call, only after the user said which.",
                    workflows: "infrastructure",
                    vernacular_kind: "specialist",
                    vernacular_reason: "Specialist context; not yet covered by the Creator Question Atlas.",
                    inputSchema: {
                        type: "object",
                        properties: {
                            section: {
                                type: "string",
                                enum: ["photos", "watch", "listen"],
                                description: "'photos', 'watch' (videos and YouTube) or 'listen' (tracks and audio).",
                            },
                            shown: {
                                type: "boolean",
                                description: "true to show the section, false to hide it.",
                            },
                        },
                        required: ["section", "shown"],
                    },
                },
                executor: this.setPageSection.bind(this),
            },
            {
                definition: {
                    name: "pica_site_get",
                    scope: "read:files",
                    audiences: ["stdio", "http"],
                    tier: "read",
                    description: "Use when the user wants to build or check their public page: 'PICA, build my site', 'I want to showcase my work', 'make me a website', 'what does my page show?'. " +
                        "Says whether the page is live, its address, and exactly what visitors see; bio_is_last_tool_text says if the bio is still a tool's text. Start the build here. " +
                        "Then: pica_site_address_check and pica_site_profile_set for the address and words, pica_site_songs_feature for songs, pica_site_images_set for photos, and pica_site_go_live for the link the user taps to put it live themselves.",
                    workflows: "infrastructure",
                    vernacular_kind: "specialist",
                    vernacular_reason: "Specialist context; not yet covered by the Creator Question Atlas.",
                    inputSchema: {
                        type: "object",
                        properties: {},
                        required: [],
                    },
                },
                executor: this.siteGet.bind(this),
            },
            {
                definition: {
                    name: "pica_site_address_check",
                    scope: "read:files",
                    audiences: ["stdio", "http"],
                    tier: "read",
                    description: "Use before setting the public page's address: checks one address (3 to 32 lowercase letters, digits and hyphens) is free. A taken or reserved one is never to be offered; suggest another from the artist's name and check that too. Set the agreed address with pica_site_profile_set.",
                    workflows: "infrastructure",
                    vernacular_kind: "specialist",
                    vernacular_reason: "Specialist context; not yet covered by the Creator Question Atlas.",
                    inputSchema: {
                        type: "object",
                        properties: {
                            name: {
                                type: "string",
                                description: "The address to check, e.g. 'sounds-like-fez'.",
                            },
                        },
                        required: ["name"],
                    },
                },
                executor: this.siteAddressCheck.bind(this),
            },
            {
                definition: {
                    name: "pica_site_profile_set",
                    scope: "write:files",
                    audiences: ["stdio", "http"],
                    tier: "write",
                    description: "Use to set the public page's address, display name, tagline, bio, website or links, after showing the user the exact text and they agreed. Only the fields given change. " +
                        "Changing the address of a live page makes the old address stop working: the answer says so, and tell the user. Links are https URLs keyed by service (streaming_spotify, social_instagram, …). Check a new address first with pica_site_address_check.",
                    workflows: "infrastructure",
                    vernacular_kind: "specialist",
                    vernacular_reason: "Specialist context; not yet covered by the Creator Question Atlas.",
                    inputSchema: {
                        type: "object",
                        properties: {
                            address: {
                                type: "string",
                                description: "The page's address, checked free first.",
                            },
                            display_name: {
                                type: "string",
                                description: "The name the page shows.",
                            },
                            tagline: {
                                type: ["string", "null"],
                                description: "One line under the name; null clears it.",
                            },
                            bio: {
                                type: ["string", "null"],
                                description: "The bio, exactly as the user agreed; null clears it.",
                            },
                            website: {
                                type: ["string", "null"],
                                description: "An https link; null clears it.",
                            },
                            links: {
                                type: "object",
                                description: "Streaming and social links: e.g. { streaming_spotify: 'https://…' }; null clears one.",
                            },
                        },
                        required: [],
                    },
                },
                executor: this.siteProfileSet.bind(this),
            },
            {
                definition: {
                    name: "pica_site_songs_feature",
                    scope: "write:files",
                    audiences: ["stdio", "http"],
                    tier: "write",
                    description: "Use when the user names songs to show on their public page: features 1 to 10 named songs, by id (find them with pica_works_query). Each one not yet public is made public, and the answer lists them. " +
                        "Never every song at once: only the songs the user named, at most 10 per call. See what the page shows with pica_site_get.",
                    workflows: "infrastructure",
                    vernacular_kind: "specialist",
                    vernacular_reason: "Specialist context; not yet covered by the Creator Question Atlas.",
                    inputSchema: {
                        type: "object",
                        properties: {
                            work_ids: {
                                type: "array",
                                items: { type: "string" },
                                minItems: 1,
                                maxItems: 10,
                                description: "The ids of the 1 to 10 songs the user named.",
                            },
                        },
                        required: ["work_ids"],
                    },
                },
                executor: this.siteSongsFeature.bind(this),
            },
            {
                definition: {
                    name: "pica_site_go_live",
                    scope: "write:files",
                    audiences: ["stdio", "http"],
                    tier: "write",
                    description: "Use to switch the public page on or off. The first time a page goes live, the person must say yes themselves on PICA: the answer then gives a link to send them, and the page stays off until they tap. After that, this switches it directly. Switching off always works. Show the user what goes public first with pica_site_get.",
                    workflows: "infrastructure",
                    vernacular_kind: "specialist",
                    vernacular_reason: "Specialist context; not yet covered by the Creator Question Atlas.",
                    inputSchema: {
                        type: "object",
                        properties: {
                            live: {
                                type: "boolean",
                                description: "true to put the page live, false to switch it off.",
                            },
                        },
                        required: ["live"],
                    },
                },
                executor: this.siteGoLive.bind(this),
            },
        ];
    }
    async searchMultimedia(args) {
        const result = await this.pica.multimedia.search({
            query: args.query,
            content_type: args.content_type,
            classification: args.classification,
            is_published: args.is_published,
            work_id: args.work_id,
            person_id: args.person_id,
            limit: args.limit,
            offset: args.offset,
        });
        return formatList(result.data || [], { total: result.total || 0 });
    }
    async inspectMultimedia(args) {
        const item = await this.pica.multimedia.get(args.id ?? args.multimedia_id);
        return formatSuccess("Media item retrieved", item);
    }
    async createMultimedia(args) {
        const item = await this.pica.multimedia.create(args);
        return formatSuccess("Multimedia item created", item);
    }
    async importFromUrl(args) {
        const result = await this.pica.multimedia.importFromUrl({
            url: args.url,
            title: args.title,
            source: args.source,
            work_id: args.work_id,
            person_id: args.person_id,
        });
        // The receipts, not just the row. `via` says whether the URL was a
        // direct image or a page whose og:image was followed — the difference
        // an agent needs when a paste "worked" but pointed at a page. And when
        // person_id / work_id were passed, the follow-on writes can fail while
        // the import itself succeeds, so their outcome belongs in the summary
        // text an LLM reads, not only in the JSON below it.
        const { item, via, profile_image: profileImage, work_link: workLink, } = result;
        let summary = `Imported from URL (${via}): "${item.title || args.url}". Multimedia ID: ${item.id}`;
        if (profileImage) {
            summary += profileImage.set
                ? ` Profile image set on person ${profileImage.person_id}.`
                : ` Profile image NOT set (${profileImage.code ?? "UNKNOWN"}): ${profileImage.reason ?? "no reason given"}`;
        }
        if (workLink) {
            summary += workLink.linked
                ? ` Linked to work ${workLink.work_id}.`
                : ` Work link failed: ${workLink.reason ?? "no reason given"}`;
        }
        // Pass the WHOLE result, so structuredContent.data carries `via`,
        // `source_url`, `profile_image`, `work_link` and `item` for a machine
        // reader as well as the summary above for a human one.
        return formatSuccess(summary, result);
    }
    async linkYoutube(args) {
        const item = await this.pica.multimedia.linkYoutube({
            youtube_video_id: args.youtube_video_id,
            title: args.title,
            classification: args.classification,
            work_id: args.work_id,
            work_relationship_type: args.work_relationship_type,
        });
        return formatSuccess(`YouTube video linked: "${item.title || args.youtube_video_id}". Multimedia ID: ${item.id}`, item);
    }
    async linkWork(args) {
        const result = await this.pica.multimedia.linkWork(args.multimedia_id, args.work_id, args.relationship_type, args.notes);
        return formatSuccess(`Multimedia ${args.multimedia_id} linked to work ${args.work_id} as "${args.relationship_type}".`, result);
    }
    async setSiteImage(args) {
        if (args.slot !== "hero" && args.slot !== "profile") {
            return formatValidationError({
                slot: 'must be "hero" (the main photo) or "profile" (the profile picture)',
            });
        }
        if (args.photo_id !== null &&
            (typeof args.photo_id !== "string" || args.photo_id.trim() === "")) {
            return formatValidationError({
                photo_id: "must be a photo's id, or null to remove the pick",
            });
        }
        const result = await this.pica.multimedia.setSiteImage(args.slot, args.photo_id);
        return formatSuccess(siteImageSentence(result), result);
    }
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    async takeOffPage(args) {
        const id = oneItemId(args);
        if (!id)
            return oneItemRefusal();
        const result = await this.pica.multimedia.takeOffPage(id);
        return formatSuccess(pageItemSentence(result), result);
    }
    async siteGet() {
        const result = await this.pica.multimedia.getSite();
        return formatSuccess(siteStateSentence(result), result);
    }
    async siteAddressCheck(args) {
        if (typeof args.name !== "string" || args.name.trim() === "") {
            return formatValidationError({ name: "must be the address to check" });
        }
        const result = await this.pica.multimedia.checkSiteAddress(args.name);
        return formatSuccess(siteAddressSentence(result), result);
    }
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    async siteProfileSet(args) {
        const keys = [
            "address",
            "display_name",
            "tagline",
            "bio",
            "website",
            "links",
        ];
        const input = Object.fromEntries(keys.filter((k) => k in args).map((k) => [k, args[k]]));
        if (Object.keys(input).length === 0) {
            return formatValidationError({
                fields: "give at least one field to set",
            });
        }
        const result = await this.pica.multimedia.setSiteProfile(input);
        return formatSuccess(siteProfileSentence(result), result);
    }
    async siteSongsFeature(args) {
        const ids = args.work_ids;
        if (!Array.isArray(ids) ||
            ids.length < 1 ||
            ids.length > 10 ||
            !ids.every((id) => typeof id === "string" && id.trim() !== "")) {
            return formatValidationError({
                work_ids: "must be 1 to 10 song ids the user named; never all songs",
            });
        }
        const result = await this.pica.multimedia.featureSiteSongs(ids);
        return formatSuccess(siteSongsSentence(result), result);
    }
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    async siteGoLive(args) {
        if (typeof args.live !== "boolean") {
            return formatValidationError({ live: "must be true or false" });
        }
        const result = await this.pica.multimedia.setSiteLive(args.live);
        return formatSuccess(siteLiveSentence(result), result);
    }
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    async setPageSection(args) {
        if (!Object.hasOwn(SECTION_ITEMS, args.section)) {
            return formatValidationError({
                section: 'must be one of "photos", "watch" or "listen"; one section per call',
            });
        }
        if (typeof args.shown !== "boolean") {
            return formatValidationError({ shown: "must be true or false" });
        }
        const result = await this.pica.multimedia.setPageSection(args.section, args.shown);
        return formatSuccess(pageSectionSentence(result), result);
    }
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    async putBackOnPage(args) {
        const id = oneItemId(args);
        if (!id)
            return oneItemRefusal();
        const result = await this.pica.multimedia.putBackOnPage(id);
        return formatSuccess(pageItemSentence(result), result);
    }
}
/** The page's public address: its own host on withpica.com, else /p/<address>. */
export function pageUrl(address) {
    const base = webBaseUrl();
    return /^https:\/\/(www\.)?withpica\.com$/.test(base)
        ? `https://${address}.withpica.com`
        : `${base}/p/${address}`;
}
/** The answer for pica_site_get. Exported for the tool's tests. */
export function siteStateSentence(s) {
    const parts = [];
    if (!s.address)
        parts.push("your public page has no address yet.");
    else if (s.live)
        parts.push(`your public page is live at ${pageUrl(s.address)}.`);
    else
        parts.push(`your public page is off; its address will be ${pageUrl(s.address)}.`);
    const m = s.summary;
    const n = (k, one, many) => `${k} ${k === 1 ? one : many}`;
    parts.push(`it shows ${n(m.works.length, "song", "songs")}, ${n(m.audioFiles.length, "audio track", "audio tracks")}, ${n(m.media.length, "photo or video", "photos and videos")} and ${n(m.tourDates.length, "show", "shows")}` +
        (m.organisation.bio ? "; it has a bio." : "; it has no bio yet."));
    if (s.live === false && s.address && !s.confirmed)
        parts.push("the first time it goes live, the person says yes themselves on PICA.");
    return parts.join(" ");
}
/** The answer for pica_site_address_check. Exported for the tool's tests. */
export function siteAddressSentence(c) {
    if (c.free)
        return c.yours
            ? `${c.address} is already your page's address.`
            : `${c.address} is free.`;
    return c.reason === "taken"
        ? `${c.address} is taken; suggest another.`
        : c.reason === "reserved"
            ? `${c.address} is reserved; suggest another.`
            : `${c.address} can't be an address: use 3 to 32 lowercase letters, digits and hyphens, starting and ending with a letter or digit.`;
}
/** The answer for pica_site_profile_set. Exported for the tool's tests. */
export function siteProfileSentence(r) {
    const parts = ["saved."];
    if (r.saved.display_name !== undefined)
        parts.push(`the page's name is "${r.saved.display_name}".`);
    if (r.saved.tagline !== undefined)
        parts.push(r.saved.tagline
            ? `the tagline reads "${r.saved.tagline}".`
            : "the tagline was cleared.");
    if (r.saved.bio !== undefined)
        parts.push(r.saved.bio
            ? `the bio now reads: "${r.saved.bio}"`
            : "the bio was cleared.");
    if (r.saved.website !== undefined)
        parts.push(r.saved.website
            ? `the website is ${r.saved.website}.`
            : "the website was cleared.");
    if (r.saved.links)
        parts.push("the links were saved.");
    if (r.address_changed && r.address) {
        parts.push(`the page's address is now ${pageUrl(r.address)}.`);
        if (r.previous_address)
            parts.push(`the old address, ${pageUrl(r.previous_address)}, stops working: anyone with that link won't reach the page.`);
    }
    return parts.join(" ");
}
/** The answer for pica_site_songs_feature. Exported for the tool's tests. */
export function siteSongsSentence(r) {
    const name = (s) => s.title ? `"${s.title}"` : `song ${s.id}`;
    const parts = [
        `featured on your public page: ${r.songs.map(name).join(", ")}.`,
    ];
    const made = r.songs.filter((s) => s.made_public);
    if (made.length > 0)
        parts.push(`${made.length === 1 ? "this song wasn't" : "these songs weren't"} public before and ${made.length === 1 ? "is" : "are"} now: ${made.map(name).join(", ")}.`);
    return parts.join(" ");
}
/** The answer for pica_site_go_live. Exported for the tool's tests. */
export function siteLiveSentence(r) {
    if (r.needs_person_yes)
        return `your page is ready, but it goes live only once you say yes yourself: open ${r.yes_link} and tap "put my page live". until then it stays off.`;
    if (r.live && r.address)
        return `your page is live at ${pageUrl(r.address)}.`;
    return "your page is off: nobody can see it until it's switched back on.";
}
/** The three switchable sections; anything else is refused before any call. */
const SECTION_ITEMS = {
    photos: ["photo", "photos"],
    watch: ["video", "videos"],
    listen: ["track", "tracks"],
};
/** The answer for a section switch. Exported for the tool's tests. */
export function pageSectionSentence(result) {
    const [one, many] = SECTION_ITEMS[result.section];
    const count = (n, oneWord, manyWord) => `${n} ${n === 1 ? oneWord : manyWord}`;
    if (result.shown) {
        const upTo = result.items_at_most ? "up to " : "";
        return result.items === 0
            ? `your ${result.section} section is now shown on your public page; it has nothing in it yet.`
            : `your ${result.section} section is now shown on your public page: ${upTo}${count(result.items, one, many)} show there.`;
    }
    const parts = [`your ${result.section} section is hidden from your page.`];
    const linked = result.linked_items ?? result.items;
    if (linked > 0) {
        // Listen's linked items are Spotify tracks; audio files are counted apart.
        const things = result.section === "listen"
            ? count(linked, "spotify track", "spotify tracks")
            : count(linked, one, many);
        parts.push(`${things} ${linked === 1 ? "is" : "are"} still public at ${linked === 1 ? "its" : "their"} own ${linked === 1 ? "link" : "links"}; to take one off for good, ask, or use the list at ${pageListUrl()}.`);
    }
    const audio = result.audio_files ?? 0;
    if (audio > 0) {
        parts.push(`${count(audio, "audio file", "audio files")} ${audio === 1 ? "is" : "are"} no longer heard anywhere public.`);
    }
    return parts.join(" ");
}
/** Exactly one item's id, or null: a list or anything else is refused. */
function oneItemId(args) {
    const id = args.multimedia_id;
    return typeof id === "string" && id.trim() !== "" ? id : null;
}
function oneItemRefusal() {
    return formatValidationError({
        multimedia_id: "must be one item's id; one item per call",
    });
}
/** Where a person sees what is on their page and puts things back. */
export function pageListUrl() {
    return `${webBaseUrl()}/settings?tab=profile#public-page`;
}
/** The answer for a take-off or put-back. Exported for the tool's tests. */
export function pageItemSentence(result) {
    const name = result.title ? `"${result.title}"` : `item ${result.id}`;
    if (!result.on_page) {
        return result.changed
            ? `${name} is no longer on your public page. it's still in your catalogue. to put it back, ask, or use the list at ${pageListUrl()}.`
            : `${name} wasn't on your public page, so nothing changed.`;
    }
    if (result.section_hidden) {
        return `${name} is public${result.changed ? " again" : ""}, but your page hides that section, so it isn't shown there. to show the section, ask, or use its switch at ${pageListUrl()}.`;
    }
    return result.changed
        ? `${name} is now on your public page.`
        : `${name} was already on your public page, so nothing changed.`;
}
const SLOT_WORDS = { hero: "main photo", profile: "profile picture" };
/** The answer, in words to pass on. Exported for the tool's tests. */
export function siteImageSentence(result) {
    const slot = SLOT_WORDS[result.slot];
    const parts = [
        result.photo_id
            ? `the ${slot} on your public page is now photo ${result.photo_id}.`
            : `the ${slot} was removed from your public page.`,
    ];
    if (result.published_now) {
        parts.push("that photo wasn't public before: it is now, and it also shows among your page's photos.");
    }
    if (result.replaced?.still_public) {
        parts.push(`the photo it replaced (${result.replaced.id}) is still public, among your page's photos. ` +
            `to take it off the page too, ask, or use the list at ${pageListUrl()}.`);
    }
    return parts.join(" ");
}
//# sourceMappingURL=multimedia.js.map