Skip to main content

media_tools/
tools.rs

1//! Agent tool adapters for media discovery, preferences and activity.
2use std::str::FromStr;
3
4use agent_runtime::{Tool, ToolContext, ToolDefinition, ToolError, ToolRegistry};
5use agent_storage::{FamilyId, UserId};
6use async_trait::async_trait;
7use chrono::Utc;
8use serde::Deserialize;
9use serde_json::{Value, json};
10
11use crate::{
12    ContentRestrictions, FamilyMediaPreferences, MediaConfig, MediaKind, MediaProfile,
13    MediaProfileId, MediaRating, MediaStore, MediaWatchEvent, ProfilePreferences,
14    RecommendationContext, RecommendationCriteria, TmdbClient, TraktSyncService,
15    WatchHistorySource, WatchmodeClient,
16};
17
18/// Dependencies shared by the registered media tools.
19#[derive(Clone)]
20pub struct MediaToolServices {
21    store: MediaStore,
22    config: MediaConfig,
23    tmdb: Option<TmdbClient>,
24    watchmode: Option<WatchmodeClient>,
25    recommendations: Option<crate::RecommendationService>,
26    sync: Option<TraktSyncService>,
27}
28
29impl MediaToolServices {
30    pub fn new(
31        store: MediaStore,
32        config: MediaConfig,
33        tmdb: Option<TmdbClient>,
34        watchmode: Option<WatchmodeClient>,
35        sync: Option<TraktSyncService>,
36    ) -> Self {
37        let recommendations = tmdb.as_ref().and_then(|tmdb| {
38            crate::RecommendationService::new(
39                store.clone(),
40                tmdb.clone(),
41                watchmode.clone(),
42                config.clone(),
43            )
44            .ok()
45        });
46        Self {
47            store,
48            config,
49            tmdb,
50            watchmode,
51            recommendations,
52            sync,
53        }
54    }
55}
56
57/// Register the complete media tool surface in the agent's executable registry.
58pub fn register_media_tools(
59    registry: &mut ToolRegistry,
60    services: MediaToolServices,
61) -> Result<(), String> {
62    let tools = [
63        (
64            "media_profiles",
65            "List media profiles in the authenticated family. Use this to ask who is watching.",
66            json!({
67                "type":"object",
68                "properties":{
69                    "action":{"type":"string","enum":["list","create","update","delete"]},
70                    "profile_id":{"type":"string"},
71                    "name":{"type":"string","minLength":1},
72                    "user_id":{"type":["string","null"]},
73                    "active":{"type":"boolean"}
74                },
75                "additionalProperties":false
76            }),
77            MediaAction::Profiles,
78        ),
79        (
80            "media_recommend",
81            "Recommend movies and TV for explicitly selected family participants.",
82            json!({
83                "type":"object",
84                "properties":{
85                    "participant_ids":{"type":"array","items":{"type":"string"},"minItems":1},
86                    "criteria":{"type":"object"},
87                    "watched_policy":{"type":"string","enum":["any_participant","all_participants","include_all"]}
88                },
89                "required":["participant_ids"],
90                "additionalProperties":false
91            }),
92            MediaAction::Recommend,
93        ),
94        (
95            "media_search",
96            "Search the TMDB catalogue for movies or TV shows.",
97            json!({
98                "type":"object",
99                "properties":{
100                    "query":{"type":"string","minLength":1},
101                    "kind":{"type":"string","enum":["movie","tv_show"]}
102                },
103                "required":["query"],
104                "additionalProperties":false
105            }),
106            MediaAction::Search,
107        ),
108        (
109            "media_details",
110            "Retrieve normalized TMDB details for a movie or TV show.",
111            json!({
112                "type":"object",
113                "properties":{
114                    "tmdb_id":{"type":"integer","minimum":1},
115                    "kind":{"type":"string","enum":["movie","tv_show"]}
116                },
117                "required":["tmdb_id","kind"],
118                "additionalProperties":false
119            }),
120            MediaAction::Details,
121        ),
122        (
123            "media_availability",
124            "Find Spanish streaming offers, including subscription, rent, buy, free and ad-supported options.",
125            json!({
126                "type":"object",
127                "properties":{
128                    "tmdb_id":{"type":"integer","minimum":1},
129                    "kind":{"type":"string","enum":["movie","tv_show"]}
130                },
131                "required":["tmdb_id","kind"],
132                "additionalProperties":false
133            }),
134            MediaAction::Availability,
135        ),
136        (
137            "media_watch_history",
138            "Read the authenticated user's viewing history, or mark a movie/show as watched on their explicit request. mark_watched requires their linked Trakt account. Omit profile_id to use their personal media profile.",
139            json!({
140                "type":"object",
141                "properties":{
142                    "action":{"type":"string","enum":["list","mark_watched"]},
143                    "profile_id":{"type":"string"},
144                    "tmdb_id":{"type":"integer","minimum":1},
145                    "kind":{"type":"string","enum":["movie","tv_show"]}
146                },
147                "additionalProperties":false
148            }),
149            MediaAction::History,
150        ),
151        (
152            "media_watchlist",
153            "Read the linked Trakt watchlist, or add/remove titles on the user's explicit request. Omit profile_id to use their personal media profile; writes require that profile's own Trakt connection.",
154            json!({
155                "type":"object",
156                "properties":{
157                    "action":{"type":"string","enum":["list","add","remove"]},
158                    "profile_id":{"type":"string"},
159                    "tmdb_id":{"type":"integer","minimum":1},
160                    "kind":{"type":"string","enum":["movie","tv_show"]}
161                },
162                "additionalProperties":false
163            }),
164            MediaAction::Watchlist,
165        ),
166        (
167            "media_rate",
168            "Record a 0–5 rating on the user's explicit request and write it through to Trakt when the selected profile has the caller's Trakt account linked. Omit profile_id to use their personal media profile.",
169            json!({
170                "type":"object",
171                "properties":{
172                    "profile_id":{"type":"string"},
173                    "tmdb_id":{"type":"integer","minimum":1},
174                    "kind":{"type":"string","enum":["movie","tv_show"]},
175                    "rating":{"type":"number","minimum":0,"maximum":5}
176                },
177                "required":["tmdb_id","kind","rating"],
178                "additionalProperties":false
179            }),
180            MediaAction::Rate,
181        ),
182        (
183            "media_preferences",
184            "Read or update explicit family/profile preferences and hard content restrictions.",
185            json!({
186                "type":"object",
187                "properties":{
188                    "action":{"type":"string","enum":["get","update"]},
189                    "scope":{"type":"string","enum":["family","profile"]},
190                    "profile_id":{"type":"string"},
191                    "preferences":{"type":"object"},
192                    "restrictions":{"type":"object"}
193                },
194                "required":["action","scope"],
195                "additionalProperties":false
196            }),
197            MediaAction::Preferences,
198        ),
199        (
200            "media_sync_history",
201            "Synchronize the authenticated user's personal Trakt profile. Omit profile_id to use their personal media profile; only provide it for an explicitly selected family-managed profile.",
202            json!({
203                "type":"object",
204                "properties":{"profile_id":{"type":"string"}},
205                "additionalProperties":false
206            }),
207            MediaAction::SyncHistory,
208        ),
209    ];
210
211    for (name, description, parameters, action) in tools {
212        registry
213            .register(
214                ToolDefinition {
215                    name: name.into(),
216                    description: description.into(),
217                    parameters,
218                },
219                MediaTool {
220                    services: services.clone(),
221                    action,
222                },
223            )
224            .map_err(|error| error.to_string())?;
225    }
226    Ok(())
227}
228
229#[derive(Clone, Copy)]
230enum MediaAction {
231    Profiles,
232    Recommend,
233    Search,
234    Details,
235    Availability,
236    History,
237    Watchlist,
238    Rate,
239    Preferences,
240    SyncHistory,
241}
242
243struct MediaTool {
244    services: MediaToolServices,
245    action: MediaAction,
246}
247
248#[async_trait]
249impl Tool for MediaTool {
250    async fn execute(&self, context: &ToolContext, arguments: Value) -> Result<String, ToolError> {
251        let result = match self.action {
252            MediaAction::Profiles => self.profiles(context, &arguments).await,
253            MediaAction::Recommend => self.recommend(context, &arguments).await,
254            MediaAction::Search => self.search(&arguments).await,
255            MediaAction::Details => self.details(&arguments).await,
256            MediaAction::Availability => self.availability(&arguments).await,
257            MediaAction::History => self.history(context, &arguments).await,
258            MediaAction::Watchlist => self.watchlist(context, &arguments).await,
259            MediaAction::Rate => self.rate(context, &arguments).await,
260            MediaAction::Preferences => self.preferences(context, &arguments).await,
261            MediaAction::SyncHistory => self.sync_history(context, &arguments).await,
262        };
263        result
264            .and_then(|value| serde_json::to_string(&value).map_err(|error| error.to_string()))
265            .map_err(ToolError::Execution)
266    }
267}
268
269impl MediaTool {
270    async fn profiles(&self, context: &ToolContext, args: &Value) -> Result<Value, String> {
271        let (_, family_id, role) = family_scope(context)?;
272        match args.get("action").and_then(Value::as_str).unwrap_or("list") {
273            "list" => {
274                let profiles = self
275                    .services
276                    .store
277                    .list_profiles(family_id)
278                    .await
279                    .map_err(display)?;
280                serde_json::to_value(profiles).map_err(display)
281            }
282            "create" => {
283                require_family_admin(role)?;
284                let mut profile = MediaProfile::new(family_id, required_string(args, "name")?);
285                if let Some(user_id) = args.get("user_id") {
286                    profile.user_id = parse_profile_user(context, user_id)?;
287                }
288                self.services
289                    .store
290                    .save_profile(&profile)
291                    .await
292                    .map_err(display)?;
293                serde_json::to_value(profile).map_err(display)
294            }
295            "update" => {
296                require_family_admin(role)?;
297                let profile_id = MediaProfileId::from_str(required_string(args, "profile_id")?)
298                    .map_err(display)?;
299                let mut profile = self
300                    .services
301                    .store
302                    .get_profile(family_id, profile_id)
303                    .await
304                    .map_err(display)?
305                    .ok_or_else(|| {
306                        "profile does not belong to the authenticated family".to_owned()
307                    })?;
308                if let Some(name) = args.get("name").and_then(Value::as_str) {
309                    profile.name = name.to_owned();
310                }
311                if let Some(active) = args.get("active").and_then(Value::as_bool) {
312                    profile.active = active;
313                }
314                if let Some(user_id) = args.get("user_id") {
315                    profile.user_id = parse_profile_user(context, user_id)?;
316                }
317                self.services
318                    .store
319                    .save_profile(&profile)
320                    .await
321                    .map_err(display)?;
322                serde_json::to_value(profile).map_err(display)
323            }
324            "delete" => {
325                require_family_admin(role)?;
326                let profile_id = MediaProfileId::from_str(required_string(args, "profile_id")?)
327                    .map_err(display)?;
328                if self
329                    .services
330                    .store
331                    .get_external_connection_link(profile_id, "trakt")
332                    .await
333                    .map_err(display)?
334                    .is_some()
335                {
336                    return Err("unlink the profile's Trakt account before deleting it".into());
337                }
338                self.services
339                    .store
340                    .delete_profile(family_id, profile_id)
341                    .await
342                    .map_err(display)?;
343                Ok(json!({"deleted_profile_id": profile_id.to_string()}))
344            }
345            _ => Err("action must be list, create, update or delete".into()),
346        }
347    }
348
349    async fn recommend(&self, context: &ToolContext, args: &Value) -> Result<Value, String> {
350        let (_, family_id, _) = family_scope(context)?;
351        let service = self.services.recommendations.as_ref().ok_or_else(|| {
352            "Media recommendations require configured TMDB and Watchmode API keys".to_owned()
353        })?;
354        let participant_ids = string_array(args, "participant_ids")?
355            .iter()
356            .map(|value| MediaProfileId::from_str(value).map_err(display))
357            .collect::<Result<Vec<_>, _>>()?;
358        let criteria = args
359            .get("criteria")
360            .cloned()
361            .map(serde_json::from_value::<RecommendationCriteria>)
362            .transpose()
363            .map_err(display)?
364            .unwrap_or_default();
365        let watched_policy = args
366            .get("watched_policy")
367            .cloned()
368            .map(serde_json::from_value)
369            .transpose()
370            .map_err(display)?;
371        let context = RecommendationContext {
372            family_id,
373            participants: participant_ids,
374            criteria,
375            watched_policy,
376        };
377        let recommendations = service.recommend(&context).await.map_err(display)?;
378        serde_json::to_value(recommendations).map_err(display)
379    }
380
381    async fn search(&self, args: &Value) -> Result<Value, String> {
382        let tmdb = self.tmdb()?;
383        let query = required_string(args, "query")?;
384        let page = match args.get("kind").and_then(Value::as_str) {
385            Some("movie") => tmdb.search_movies(query, 1).await.map_err(display)?,
386            Some("tv_show") => tmdb.search_tv(query, 1).await.map_err(display)?,
387            Some(_) => return Err("kind must be movie or tv_show".into()),
388            None => {
389                let movies = tmdb.search_movies(query, 1).await.map_err(display)?;
390                let shows = tmdb.search_tv(query, 1).await.map_err(display)?;
391                let mut items = movies.items;
392                items.extend(shows.items);
393                return serde_json::to_value(items).map_err(display);
394            }
395        };
396        serde_json::to_value(page.items).map_err(display)
397    }
398
399    async fn details(&self, args: &Value) -> Result<Value, String> {
400        let tmdb = self.tmdb()?;
401        let id = required_u64(args, "tmdb_id")?;
402        let kind = parse_kind(required_string(args, "kind")?)?;
403        let item = match kind {
404            MediaKind::Movie => tmdb.movie_details(id).await,
405            MediaKind::TvShow => tmdb.tv_details(id).await,
406        }
407        .map_err(display)?;
408        serde_json::to_value(item).map_err(display)
409    }
410
411    async fn availability(&self, args: &Value) -> Result<Value, String> {
412        let id = required_u64(args, "tmdb_id")?;
413        let kind = parse_kind(required_string(args, "kind")?)?;
414        let mut offers = if let Some(watchmode) = &self.services.watchmode {
415            match watchmode
416                .offers_for_tmdb_id(id, kind, &self.services.config.country)
417                .await
418            {
419                Ok(offers) => offers,
420                Err(_) => {
421                    tracing::warn!(
422                        provider = "watchmode",
423                        "availability lookup failed; falling back to TMDB watch providers"
424                    );
425                    Vec::new()
426                }
427            }
428        } else {
429            Vec::new()
430        };
431        if offers.is_empty() {
432            offers = self
433                .tmdb()?
434                .watch_providers(id, kind, &self.services.config.country)
435                .await
436                .map_err(display)?;
437        }
438        serde_json::to_value(offers).map_err(display)
439    }
440
441    async fn history(&self, context: &ToolContext, args: &Value) -> Result<Value, String> {
442        let action = args.get("action").and_then(Value::as_str).unwrap_or("list");
443        if action == "mark_watched" {
444            let profile_id = self
445                .require_profile(
446                    context,
447                    args.get("profile_id").and_then(Value::as_str),
448                    true,
449                )
450                .await?;
451            let user_id = authenticated_user_id(context)?;
452            let tmdb_id = required_u64(args, "tmdb_id")?;
453            let kind = parse_kind(required_string(args, "kind")?)?;
454            let item = match kind {
455                MediaKind::Movie => self.tmdb()?.movie_details(tmdb_id).await,
456                MediaKind::TvShow => self.tmdb()?.tv_details(tmdb_id).await,
457            }
458            .map_err(display)?;
459            let sync = self
460                .services
461                .sync
462                .as_ref()
463                .ok_or_else(|| "Trakt write synchronization is not configured".to_owned())?;
464            sync.mark_watched(user_id, profile_id, &item)
465                .await
466                .map_err(display)?;
467            return Ok(json!({
468                "action": "mark_watched",
469                "profile_id": profile_id.to_string(),
470                "item": item,
471                "trakt_synced": true
472            }));
473        }
474        if action != "list" {
475            return Err("action must be list or mark_watched".into());
476        }
477        let profile_id = self
478            .require_profile(
479                context,
480                args.get("profile_id").and_then(Value::as_str),
481                false,
482            )
483            .await?;
484        let events: Vec<MediaWatchEvent> = self
485            .services
486            .store
487            .list_watch_history(profile_id)
488            .await
489            .map_err(display)?;
490        let mut history = Vec::with_capacity(events.len());
491        for event in events {
492            let item = self
493                .services
494                .store
495                .get_media_item(event.media_item_id)
496                .await
497                .map_err(display)?;
498            history.push(json!({
499                "event": event,
500                "media_item": item,
501            }));
502        }
503        let sync_state = self
504            .services
505            .store
506            .get_provider_sync_state(profile_id, "trakt")
507            .await
508            .map_err(display)?;
509        Ok(json!({
510            "profile_id": profile_id.to_string(),
511            "events": history,
512            "trakt_sync": sync_state,
513        }))
514    }
515
516    async fn watchlist(&self, context: &ToolContext, args: &Value) -> Result<Value, String> {
517        let action = args.get("action").and_then(Value::as_str).unwrap_or("list");
518        let profile_id = self
519            .require_profile(
520                context,
521                args.get("profile_id").and_then(Value::as_str),
522                action != "list",
523            )
524            .await?;
525        match action {
526            "list" => {
527                if let Some(sync) = &self.services.sync {
528                    match sync
529                        .list_watchlist(authenticated_user_id(context)?, profile_id)
530                        .await
531                    {
532                        Ok(items) => return Ok(Value::Array(items)),
533                        Err(crate::TraktSyncError::NotLinked) => {}
534                        Err(error) => return Err(display(error)),
535                    }
536                }
537                let items = self
538                    .services
539                    .store
540                    .list_watchlist(profile_id)
541                    .await
542                    .map_err(display)?;
543                serde_json::to_value(items).map_err(display)
544            }
545            "add" | "remove" => {
546                let user_id = authenticated_user_id(context)?;
547                let tmdb_id = required_u64(args, "tmdb_id")?;
548                let kind = parse_kind(required_string(args, "kind")?)?;
549                let item = match kind {
550                    MediaKind::Movie => self.tmdb()?.movie_details(tmdb_id).await,
551                    MediaKind::TvShow => self.tmdb()?.tv_details(tmdb_id).await,
552                }
553                .map_err(display)?;
554                let sync =
555                    self.services.sync.as_ref().ok_or_else(|| {
556                        "Trakt write synchronization is not configured".to_owned()
557                    })?;
558                sync.set_watchlist_item(user_id, profile_id, &item, action == "add")
559                    .await
560                    .map_err(display)?;
561                Ok(json!({
562                    "action": action,
563                    "profile_id": profile_id.to_string(),
564                    "item": item
565                }))
566            }
567            _ => Err("action must be list, add or remove".into()),
568        }
569    }
570
571    async fn rate(&self, context: &ToolContext, args: &Value) -> Result<Value, String> {
572        let profile_id = self
573            .require_profile(
574                context,
575                args.get("profile_id").and_then(Value::as_str),
576                true,
577            )
578            .await?;
579        let user_id = authenticated_user_id(context)?;
580        let tmdb_id = required_u64(args, "tmdb_id")?;
581        let kind = parse_kind(required_string(args, "kind")?)?;
582        let rating = args
583            .get("rating")
584            .and_then(Value::as_f64)
585            .ok_or_else(|| "rating must be a number".to_owned())? as f32;
586        if !rating.is_finite() || !(0.0..=5.0).contains(&rating) {
587            return Err("rating must be between 0 and 5".into());
588        }
589        let item = match kind {
590            MediaKind::Movie => self.tmdb()?.movie_details(tmdb_id).await,
591            MediaKind::TvShow => self.tmdb()?.tv_details(tmdb_id).await,
592        }
593        .map_err(display)?;
594        let record = MediaRating {
595            profile_id,
596            media_item_id: item.id,
597            value: rating,
598            rated_at: Utc::now(),
599            source: WatchHistorySource::Eme,
600        };
601
602        let link = self
603            .services
604            .store
605            .get_external_connection_link(profile_id, "trakt")
606            .await
607            .map_err(display)?;
608        let trakt_synced = if let Some(link) = link {
609            if link.owner_id != user_id {
610                return Err(
611                    "the linked Trakt account belongs to another profile owner; only that owner can change its Trakt ratings"
612                        .into(),
613                );
614            }
615            let sync = self
616                .services
617                .sync
618                .as_ref()
619                .ok_or_else(|| "Trakt write synchronization is not configured".to_owned())?;
620            sync.push_rating(user_id, profile_id, &item, &record)
621                .await
622                .map_err(display)?;
623            true
624        } else {
625            self.services
626                .store
627                .save_media_item(&item)
628                .await
629                .map_err(display)?;
630            self.services
631                .store
632                .save_rating(&record)
633                .await
634                .map_err(display)?;
635            false
636        };
637        Ok(json!({
638            "rating": record,
639            "trakt_synced": trakt_synced
640        }))
641    }
642
643    async fn preferences(&self, context: &ToolContext, args: &Value) -> Result<Value, String> {
644        let action = required_string(args, "action")?;
645        let scope = required_string(args, "scope")?;
646        let (_user_id, family_id, role) = family_scope(context)?;
647        match (scope, action) {
648            ("family", "get") => {
649                let preferences = self
650                    .services
651                    .store
652                    .get_family_preferences(family_id)
653                    .await
654                    .map_err(display)?
655                    .unwrap_or_else(|| FamilyMediaPreferences::new(family_id));
656                serde_json::to_value(preferences).map_err(display)
657            }
658            ("family", "update") => {
659                require_family_admin(role)?;
660                let value = args
661                    .get("preferences")
662                    .cloned()
663                    .ok_or_else(|| "preferences are required for update".to_owned())?;
664                let value = set_json_field(
665                    value,
666                    "family_id",
667                    serde_json::to_value(family_id).map_err(display)?,
668                )?;
669                let mut preferences: FamilyMediaPreferences =
670                    serde_json::from_value(value).map_err(display)?;
671                preferences.family_id = family_id;
672                self.services
673                    .store
674                    .save_family_preferences(&preferences)
675                    .await
676                    .map_err(display)?;
677                serde_json::to_value(preferences).map_err(display)
678            }
679            ("profile", "get") => {
680                let profile_id = self
681                    .require_profile(context, Some(required_string(args, "profile_id")?), false)
682                    .await?;
683                let preferences = self
684                    .services
685                    .store
686                    .get_profile_preferences(profile_id)
687                    .await
688                    .map_err(display)?
689                    .unwrap_or_else(|| ProfilePreferences::new(profile_id));
690                let restrictions = self
691                    .services
692                    .store
693                    .get_content_restrictions(profile_id)
694                    .await
695                    .map_err(display)?
696                    .unwrap_or_else(|| ContentRestrictions::new(profile_id));
697                Ok(json!({"preferences": preferences, "restrictions": restrictions}))
698            }
699            ("profile", "update") => {
700                let profile_id = self
701                    .require_profile(context, Some(required_string(args, "profile_id")?), true)
702                    .await?;
703                let mut updated = false;
704                if let Some(value) = args.get("preferences") {
705                    let value = set_json_field(
706                        value.clone(),
707                        "profile_id",
708                        serde_json::to_value(profile_id).map_err(display)?,
709                    )?;
710                    let mut preferences: ProfilePreferences =
711                        serde_json::from_value(value).map_err(display)?;
712                    preferences.profile_id = profile_id;
713                    self.services
714                        .store
715                        .save_profile_preferences(&preferences)
716                        .await
717                        .map_err(display)?;
718                    updated = true;
719                }
720                if let Some(value) = args.get("restrictions") {
721                    let value = set_json_field(
722                        value.clone(),
723                        "profile_id",
724                        serde_json::to_value(profile_id).map_err(display)?,
725                    )?;
726                    let mut restrictions: ContentRestrictions =
727                        serde_json::from_value(value).map_err(display)?;
728                    restrictions.profile_id = profile_id;
729                    self.services
730                        .store
731                        .save_content_restrictions(&restrictions)
732                        .await
733                        .map_err(display)?;
734                    updated = true;
735                }
736                if !updated {
737                    return Err("preferences or restrictions are required for update".into());
738                }
739                let preferences = self
740                    .services
741                    .store
742                    .get_profile_preferences(profile_id)
743                    .await
744                    .map_err(display)?;
745                let restrictions = self
746                    .services
747                    .store
748                    .get_content_restrictions(profile_id)
749                    .await
750                    .map_err(display)?;
751                Ok(json!({"preferences": preferences, "restrictions": restrictions}))
752            }
753            _ => Err("scope must be family or profile, and action must be get or update".into()),
754        }
755    }
756
757    async fn sync_history(&self, context: &ToolContext, args: &Value) -> Result<Value, String> {
758        let profile_id = self
759            .require_profile(
760                context,
761                args.get("profile_id").and_then(Value::as_str),
762                false,
763            )
764            .await?;
765        let user_id = authenticated_user_id(context)?;
766        let sync = self
767            .services
768            .sync
769            .as_ref()
770            .ok_or_else(|| "Trakt synchronization is not configured".to_owned())?;
771        let summary = sync
772            .sync_profile(user_id, profile_id)
773            .await
774            .map_err(display)?;
775        serde_json::to_value(summary).map_err(display)
776    }
777
778    async fn require_profile(
779        &self,
780        context: &ToolContext,
781        profile_id: Option<&str>,
782        manage: bool,
783    ) -> Result<MediaProfileId, String> {
784        let user_id = authenticated_user_id(context)?;
785        let Some(profile_id) = profile_id else {
786            return self
787                .services
788                .store
789                .get_or_create_personal_profile(user_id)
790                .await
791                .map(|profile| profile.id)
792                .map_err(display);
793        };
794        let profile_id = MediaProfileId::from_str(profile_id).map_err(display)?;
795
796        if self
797            .services
798            .store
799            .get_personal_profile(user_id, profile_id)
800            .await
801            .map_err(display)?
802            .is_some()
803        {
804            return Ok(profile_id);
805        }
806
807        let family = context.family.as_ref().ok_or_else(|| {
808            "this is a family-managed media profile; select its family first".to_owned()
809        })?;
810        let family_id = parse_id::<FamilyId>(&family.family_id)?;
811        let profile: MediaProfile = self
812            .services
813            .store
814            .get_profile(family_id, profile_id)
815            .await
816            .map_err(display)?
817            .ok_or_else(|| {
818                "media profile does not belong to the authenticated user or selected family"
819                    .to_owned()
820            })?;
821        if manage && !is_family_admin(&family.family_role) && profile.user_id != Some(user_id) {
822            return Err("you are not allowed to modify this media profile".into());
823        }
824        Ok(profile_id)
825    }
826
827    fn tmdb(&self) -> Result<&TmdbClient, String> {
828        self.services
829            .tmdb
830            .as_ref()
831            .ok_or_else(|| "TMDB is not configured".to_owned())
832    }
833}
834
835fn authenticated_user_id(context: &ToolContext) -> Result<UserId, String> {
836    context
837        .user_id
838        .as_deref()
839        .ok_or_else(|| "authenticated user context is required".to_owned())
840        .and_then(parse_id::<UserId>)
841}
842
843fn family_scope(context: &ToolContext) -> Result<(UserId, FamilyId, &str), String> {
844    let user_id = authenticated_user_id(context)?;
845    let family = context
846        .family
847        .as_ref()
848        .ok_or_else(|| "an authenticated family context is required".to_owned())?;
849    let family_id = parse_id::<FamilyId>(&family.family_id)?;
850    Ok((user_id, family_id, family.family_role.as_str()))
851}
852
853fn parse_profile_user(context: &ToolContext, value: &Value) -> Result<Option<UserId>, String> {
854    if value.is_null() {
855        return Ok(None);
856    }
857    let user_id: UserId = serde_json::from_value(value.clone()).map_err(display)?;
858    let family = context
859        .family
860        .as_ref()
861        .ok_or_else(|| "an authenticated family context is required".to_owned())?;
862    if !family
863        .members
864        .iter()
865        .any(|member| member.user_id == user_id.to_string())
866    {
867        return Err("associated user must be an active member of this family".into());
868    }
869    Ok(Some(user_id))
870}
871
872fn parse_id<T: for<'de> Deserialize<'de>>(value: &str) -> Result<T, String> {
873    serde_json::from_value(Value::String(value.to_owned())).map_err(display)
874}
875
876fn require_family_admin(role: &str) -> Result<(), String> {
877    if is_family_admin(role) {
878        Ok(())
879    } else {
880        Err("family owner or admin permission is required".into())
881    }
882}
883
884fn is_family_admin(role: &str) -> bool {
885    role.eq_ignore_ascii_case("owner") || role.eq_ignore_ascii_case("admin")
886}
887
888fn required_string<'a>(args: &'a Value, name: &str) -> Result<&'a str, String> {
889    args.get(name)
890        .and_then(Value::as_str)
891        .filter(|value| !value.trim().is_empty())
892        .ok_or_else(|| format!("{name} must be a non-empty string"))
893}
894
895fn required_u64(args: &Value, name: &str) -> Result<u64, String> {
896    args.get(name)
897        .and_then(Value::as_u64)
898        .filter(|value| *value > 0)
899        .ok_or_else(|| format!("{name} must be a positive integer"))
900}
901
902fn string_array<'a>(args: &'a Value, name: &str) -> Result<Vec<&'a str>, String> {
903    args.get(name)
904        .and_then(Value::as_array)
905        .ok_or_else(|| format!("{name} must be an array"))?
906        .iter()
907        .map(|value| {
908            value
909                .as_str()
910                .filter(|value| !value.trim().is_empty())
911                .ok_or_else(|| format!("{name} must contain non-empty strings"))
912        })
913        .collect()
914}
915
916fn set_json_field(mut value: Value, field: &str, field_value: Value) -> Result<Value, String> {
917    let object = value
918        .as_object_mut()
919        .ok_or_else(|| "preferences and restrictions must be JSON objects".to_owned())?;
920    object.insert(field.to_owned(), field_value);
921    Ok(value)
922}
923
924fn parse_kind(value: &str) -> Result<MediaKind, String> {
925    match value {
926        "movie" => Ok(MediaKind::Movie),
927        "tv_show" => Ok(MediaKind::TvShow),
928        _ => Err("kind must be movie or tv_show".into()),
929    }
930}
931
932fn display(error: impl std::fmt::Display) -> String {
933    error.to_string()
934}
935
936#[cfg(test)]
937mod tests {
938    use agent_runtime::{FamilyContext, ToolDispatcher};
939    use agent_storage::{FamilyId, UserId};
940
941    use super::*;
942
943    #[tokio::test]
944    async fn personal_history_defaults_to_authenticated_users_profile_without_family() {
945        let store = MediaStore::open_in_memory().unwrap();
946        let user_id = UserId::new();
947        let services =
948            MediaToolServices::new(store.clone(), MediaConfig::default(), None, None, None);
949        let mut registry = ToolRegistry::new();
950        register_media_tools(&mut registry, services).unwrap();
951        let context = ToolContext::new(user_id.to_string());
952
953        let output = registry
954            .execute(&context, "media_watch_history", json!({}))
955            .await
956            .unwrap();
957        let history: Value = serde_json::from_str(&output).unwrap();
958        let profile = store.get_or_create_personal_profile(user_id).await.unwrap();
959
960        assert_eq!(history["profile_id"], profile.id.to_string());
961        assert_eq!(history["events"], json!([]));
962        assert!(history["trakt_sync"].is_null());
963
964        let watchlist = registry
965            .execute(&context, "media_watchlist", json!({}))
966            .await
967            .unwrap();
968        assert_eq!(
969            serde_json::from_str::<Value>(&watchlist).unwrap(),
970            json!([])
971        );
972    }
973
974    #[tokio::test]
975    async fn registers_media_tools_and_uses_trusted_family_context() {
976        let store = MediaStore::open_in_memory().unwrap();
977        let family_id = FamilyId::new();
978        let user_id = UserId::new();
979        let mut profile = MediaProfile::new(family_id, "Child");
980        profile.user_id = Some(user_id);
981        store.save_profile(&profile).await.unwrap();
982
983        let services =
984            MediaToolServices::new(store.clone(), MediaConfig::default(), None, None, None);
985        let mut registry = ToolRegistry::new();
986        register_media_tools(&mut registry, services).unwrap();
987
988        for name in [
989            "media_profiles",
990            "media_recommend",
991            "media_search",
992            "media_details",
993            "media_availability",
994            "media_watch_history",
995            "media_watchlist",
996            "media_rate",
997            "media_preferences",
998            "media_sync_history",
999        ] {
1000            assert!(registry.contains(name), "missing tool {name}");
1001        }
1002
1003        let context = ToolContext {
1004            user_id: Some(user_id.to_string()),
1005            family: Some(FamilyContext {
1006                family_id: family_id.to_string(),
1007                family_name: "Home".into(),
1008                family_role: "member".into(),
1009                relationship: "parent".into(),
1010                members: Vec::new(),
1011            }),
1012            ..ToolContext::default()
1013        };
1014        let output = registry
1015            .execute(&context, "media_profiles", json!({}))
1016            .await
1017            .unwrap();
1018        let profiles: Vec<MediaProfile> = serde_json::from_str(&output).unwrap();
1019        assert_eq!(profiles, vec![profile.clone()]);
1020
1021        let error = registry
1022            .execute(
1023                &context,
1024                "media_recommend",
1025                json!({
1026                    "participant_ids": [profile.id.to_string()],
1027                    "family_id": FamilyId::new().to_string()
1028                }),
1029            )
1030            .await
1031            .unwrap_err();
1032        assert!(matches!(error, ToolError::InvalidArguments { .. }));
1033    }
1034
1035    #[tokio::test]
1036    async fn recommendation_tool_executes_the_provider_pipeline_for_selected_profiles() {
1037        use std::time::Duration;
1038
1039        use wiremock::{
1040            Mock, MockServer, ResponseTemplate,
1041            matchers::{method, path, query_param},
1042        };
1043
1044        let tmdb_server = MockServer::start().await;
1045        Mock::given(method("GET"))
1046            .and(path("/genre/movie/list"))
1047            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1048                "genres": [{"id": 35, "name": "Comedy"}]
1049            })))
1050            .mount(&tmdb_server)
1051            .await;
1052        Mock::given(method("GET"))
1053            .and(path("/search/movie"))
1054            .and(query_param("query", "comedy"))
1055            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1056                "page": 1,
1057                "total_pages": 1,
1058                "total_results": 1,
1059                "results": [{
1060                    "id": 42,
1061                    "title": "Tool Recommendation",
1062                    "genre_ids": [35],
1063                    "release_date": "2025-01-01",
1064                    "popularity": 30.0,
1065                    "vote_average": 8.0,
1066                    "vote_count": 500
1067                }]
1068            })))
1069            .mount(&tmdb_server)
1070            .await;
1071        Mock::given(method("GET"))
1072            .and(path("/movie/42"))
1073            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1074                "id": 42,
1075                "title": "Tool Recommendation",
1076                "release_date": "2025-01-01",
1077                "genres": [{"id": 35, "name": "Comedy"}],
1078                "runtime": 95,
1079                "vote_average": 8.0,
1080                "vote_count": 500,
1081                "release_dates": {
1082                    "results": [{
1083                        "iso_3166_1": "ES",
1084                        "release_dates": [{"certification": "7"}]
1085                    }]
1086                }
1087            })))
1088            .mount(&tmdb_server)
1089            .await;
1090
1091        let watchmode_server = MockServer::start().await;
1092        Mock::given(method("GET"))
1093            .and(path("/search/"))
1094            .and(query_param("search_value", "42"))
1095            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1096                "title_results": [{"id": 9001}]
1097            })))
1098            .mount(&watchmode_server)
1099            .await;
1100        Mock::given(method("GET"))
1101            .and(path("/title/9001/sources/"))
1102            .respond_with(ResponseTemplate::new(200).set_body_json(json!([
1103                {"source_id": 203, "name": "Netflix", "type": "sub", "region": "ES", "web_url": "https://example.invalid/title"}
1104            ])))
1105            .mount(&watchmode_server)
1106            .await;
1107
1108        let store = MediaStore::open_in_memory().unwrap();
1109        let family_id = FamilyId::new();
1110        let profile = MediaProfile::new(family_id, "Selected viewer");
1111        store.save_profile(&profile).await.unwrap();
1112        let tmdb = TmdbClient::with_base_url("tmdb-key", "es-ES", "ES", tmdb_server.uri()).unwrap();
1113        let watchmode = WatchmodeClient::with_options(
1114            "watchmode-key",
1115            watchmode_server.uri(),
1116            Duration::from_secs(60),
1117        )
1118        .unwrap();
1119        let services = MediaToolServices::new(
1120            store,
1121            MediaConfig::default(),
1122            Some(tmdb),
1123            Some(watchmode),
1124            None,
1125        );
1126        let mut registry = ToolRegistry::new();
1127        register_media_tools(&mut registry, services).unwrap();
1128        let context = ToolContext {
1129            user_id: Some(UserId::new().to_string()),
1130            family: Some(FamilyContext {
1131                family_id: family_id.to_string(),
1132                family_name: "Home".into(),
1133                family_role: "member".into(),
1134                relationship: "parent".into(),
1135                members: Vec::new(),
1136            }),
1137            ..ToolContext::default()
1138        };
1139
1140        let output = registry
1141            .execute(
1142                &context,
1143                "media_recommend",
1144                json!({
1145                    "participant_ids": [profile.id.to_string()],
1146                    "criteria": {
1147                        "kinds": ["movie"],
1148                        "query": "comedy"
1149                    }
1150                }),
1151            )
1152            .await
1153            .unwrap();
1154        let recommendations: Value = serde_json::from_str(&output).unwrap();
1155        assert_eq!(recommendations.as_array().unwrap().len(), 1);
1156        assert_eq!(recommendations[0]["offers"][0]["service_name"], "Netflix");
1157        assert_eq!(
1158            recommendations[0]["history_unknown_for"][0],
1159            json!(profile.id.to_string())
1160        );
1161    }
1162
1163    #[tokio::test]
1164    async fn preference_updates_bind_ids_to_authenticated_family_and_profile() {
1165        let store = MediaStore::open_in_memory().unwrap();
1166        let family_id = FamilyId::new();
1167        let user_id = UserId::new();
1168        let mut profile = MediaProfile::new(family_id, "Viewer");
1169        profile.user_id = Some(user_id);
1170        store.save_profile(&profile).await.unwrap();
1171        let services =
1172            MediaToolServices::new(store.clone(), MediaConfig::default(), None, None, None);
1173        let mut registry = ToolRegistry::new();
1174        register_media_tools(&mut registry, services).unwrap();
1175        let context = ToolContext {
1176            user_id: Some(user_id.to_string()),
1177            family: Some(FamilyContext {
1178                family_id: family_id.to_string(),
1179                family_name: "Home".into(),
1180                family_role: "member".into(),
1181                relationship: "parent".into(),
1182                members: Vec::new(),
1183            }),
1184            ..ToolContext::default()
1185        };
1186
1187        registry
1188            .execute(
1189                &context,
1190                "media_preferences",
1191                json!({
1192                    "action": "update",
1193                    "scope": "profile",
1194                    "profile_id": profile.id.to_string(),
1195                    "preferences": {
1196                        "profile_id": MediaProfileId::new().to_string(),
1197                        "liked_genres": ["Comedy"]
1198                    }
1199                }),
1200            )
1201            .await
1202            .unwrap();
1203
1204        let preferences = store
1205            .get_profile_preferences(profile.id)
1206            .await
1207            .unwrap()
1208            .unwrap();
1209        assert_eq!(preferences.profile_id, profile.id);
1210        assert_eq!(preferences.liked_genres, vec!["Comedy"]);
1211    }
1212}