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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
import { messagingApi } from "@line/bot-sdk";
import type { LineSendResult } from "./types.js";
import { loadConfig } from "../config/config.js";
import { logVerbose } from "../globals.js";
import { recordChannelActivity } from "../infra/channel-activity.js";
import { resolveLineAccount } from "./accounts.js";

// Use the messaging API types directly
type Message = messagingApi.Message;
type TextMessage = messagingApi.TextMessage;
type ImageMessage = messagingApi.ImageMessage;
type LocationMessage = messagingApi.LocationMessage;
type FlexMessage = messagingApi.FlexMessage;
type FlexContainer = messagingApi.FlexContainer;
type TemplateMessage = messagingApi.TemplateMessage;
type QuickReply = messagingApi.QuickReply;
type QuickReplyItem = messagingApi.QuickReplyItem;

// Cache for user profiles
const userProfileCache = new Map<
  string,
  { displayName: string; pictureUrl?: string; fetchedAt: number }
>();
const PROFILE_CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes

interface LineSendOpts {
  channelAccessToken?: string;
  accountId?: string;
  verbose?: boolean;
  mediaUrl?: string;
  replyToken?: string;
}

function resolveToken(
  explicit: string | undefined,
  params: { accountId: string; channelAccessToken: string },
): string {
  if (explicit?.trim()) {
    return explicit.trim();
  }
  if (!params.channelAccessToken) {
    throw new Error(
      `LINE channel access token missing for account "${params.accountId}" (set channels.line.channelAccessToken or LINE_CHANNEL_ACCESS_TOKEN).`,
    );
  }
  return params.channelAccessToken.trim();
}

function normalizeTarget(to: string): string {
  const trimmed = to.trim();
  if (!trimmed) {
    throw new Error("Recipient is required for LINE sends");
  }

  // Strip internal prefixes
  let normalized = trimmed
    .replace(/^line:group:/i, "")
    .replace(/^line:room:/i, "")
    .replace(/^line:user:/i, "")
    .replace(/^line:/i, "");

  if (!normalized) {
    throw new Error("Recipient is required for LINE sends");
  }

  return normalized;
}

function createTextMessage(text: string): TextMessage {
  return { type: "text", text };
}

export function createImageMessage(
  originalContentUrl: string,
  previewImageUrl?: string,
): ImageMessage {
  return {
    type: "image",
    originalContentUrl,
    previewImageUrl: previewImageUrl ?? originalContentUrl,
  };
}

export function createLocationMessage(location: {
  title: string;
  address: string;
  latitude: number;
  longitude: number;
}): LocationMessage {
  return {
    type: "location",
    title: location.title.slice(0, 100), // LINE limit
    address: location.address.slice(0, 100), // LINE limit
    latitude: location.latitude,
    longitude: location.longitude,
  };
}

function logLineHttpError(err: unknown, context: string): void {
  if (!err || typeof err !== "object") {
    return;
  }
  const { status, statusText, body } = err as {
    status?: number;
    statusText?: string;
    body?: string;
  };
  if (typeof body === "string") {
    const summary = status ? `${status} ${statusText ?? ""}`.trim() : "unknown status";
    logVerbose(`line: ${context} failed (${summary}): ${body}`);
  }
}

export async function sendMessageLine(
  to: string,
  text: string,
  opts: LineSendOpts = {},
): Promise<LineSendResult> {
  const cfg = loadConfig();
  const account = resolveLineAccount({
    cfg,
    accountId: opts.accountId,
  });
  const token = resolveToken(opts.channelAccessToken, account);
  const chatId = normalizeTarget(to);

  const client = new messagingApi.MessagingApiClient({
    channelAccessToken: token,
  });

  const messages: Message[] = [];

  // Add media if provided
  if (opts.mediaUrl?.trim()) {
    messages.push(createImageMessage(opts.mediaUrl.trim()));
  }

  // Add text message
  if (text?.trim()) {
    messages.push(createTextMessage(text.trim()));
  }

  if (messages.length === 0) {
    throw new Error("Message must be non-empty for LINE sends");
  }

  // Use reply if we have a reply token, otherwise push
  if (opts.replyToken) {
    await client.replyMessage({
      replyToken: opts.replyToken,
      messages,
    });

    recordChannelActivity({
      channel: "line",
      accountId: account.accountId,
      direction: "outbound",
    });

    if (opts.verbose) {
      logVerbose(`line: replied to ${chatId}`);
    }

    return {
      messageId: "reply",
      chatId,
    };
  }

  // Push message (for proactive messaging)
  await client.pushMessage({
    to: chatId,
    messages,
  });

  recordChannelActivity({
    channel: "line",
    accountId: account.accountId,
    direction: "outbound",
  });

  if (opts.verbose) {
    logVerbose(`line: pushed message to ${chatId}`);
  }

  return {
    messageId: "push",
    chatId,
  };
}

export async function pushMessageLine(
  to: string,
  text: string,
  opts: LineSendOpts = {},
): Promise<LineSendResult> {
  // Force push (no reply token)
  return sendMessageLine(to, text, { ...opts, replyToken: undefined });
}

export async function replyMessageLine(
  replyToken: string,
  messages: Message[],
  opts: { channelAccessToken?: string; accountId?: string; verbose?: boolean } = {},
): Promise<void> {
  const cfg = loadConfig();
  const account = resolveLineAccount({
    cfg,
    accountId: opts.accountId,
  });
  const token = resolveToken(opts.channelAccessToken, account);

  const client = new messagingApi.MessagingApiClient({
    channelAccessToken: token,
  });

  await client.replyMessage({
    replyToken,
    messages,
  });

  recordChannelActivity({
    channel: "line",
    accountId: account.accountId,
    direction: "outbound",
  });

  if (opts.verbose) {
    logVerbose(`line: replied with ${messages.length} messages`);
  }
}

export async function pushMessagesLine(
  to: string,
  messages: Message[],
  opts: { channelAccessToken?: string; accountId?: string; verbose?: boolean } = {},
): Promise<LineSendResult> {
  if (messages.length === 0) {
    throw new Error("Message must be non-empty for LINE sends");
  }

  const cfg = loadConfig();
  const account = resolveLineAccount({
    cfg,
    accountId: opts.accountId,
  });
  const token = resolveToken(opts.channelAccessToken, account);
  const chatId = normalizeTarget(to);

  const client = new messagingApi.MessagingApiClient({
    channelAccessToken: token,
  });

  await client
    .pushMessage({
      to: chatId,
      messages,
    })
    .catch((err) => {
      logLineHttpError(err, "push message");
      throw err;
    });

  recordChannelActivity({
    channel: "line",
    accountId: account.accountId,
    direction: "outbound",
  });

  if (opts.verbose) {
    logVerbose(`line: pushed ${messages.length} messages to ${chatId}`);
  }

  return {
    messageId: "push",
    chatId,
  };
}

export function createFlexMessage(
  altText: string,
  contents: messagingApi.FlexContainer,
): messagingApi.FlexMessage {
  return {
    type: "flex",
    altText,
    contents,
  };
}

/**
 * Push an image message to a user/group
 */
export async function pushImageMessage(
  to: string,
  originalContentUrl: string,
  previewImageUrl?: string,
  opts: { channelAccessToken?: string; accountId?: string; verbose?: boolean } = {},
): Promise<LineSendResult> {
  const cfg = loadConfig();
  const account = resolveLineAccount({
    cfg,
    accountId: opts.accountId,
  });
  const token = resolveToken(opts.channelAccessToken, account);
  const chatId = normalizeTarget(to);

  const client = new messagingApi.MessagingApiClient({
    channelAccessToken: token,
  });

  const imageMessage = createImageMessage(originalContentUrl, previewImageUrl);

  await client.pushMessage({
    to: chatId,
    messages: [imageMessage],
  });

  recordChannelActivity({
    channel: "line",
    accountId: account.accountId,
    direction: "outbound",
  });

  if (opts.verbose) {
    logVerbose(`line: pushed image to ${chatId}`);
  }

  return {
    messageId: "push",
    chatId,
  };
}

/**
 * Push a location message to a user/group
 */
export async function pushLocationMessage(
  to: string,
  location: {
    title: string;
    address: string;
    latitude: number;
    longitude: number;
  },
  opts: { channelAccessToken?: string; accountId?: string; verbose?: boolean } = {},
): Promise<LineSendResult> {
  const cfg = loadConfig();
  const account = resolveLineAccount({
    cfg,
    accountId: opts.accountId,
  });
  const token = resolveToken(opts.channelAccessToken, account);
  const chatId = normalizeTarget(to);

  const client = new messagingApi.MessagingApiClient({
    channelAccessToken: token,
  });

  const locationMessage = createLocationMessage(location);

  await client.pushMessage({
    to: chatId,
    messages: [locationMessage],
  });

  recordChannelActivity({
    channel: "line",
    accountId: account.accountId,
    direction: "outbound",
  });

  if (opts.verbose) {
    logVerbose(`line: pushed location to ${chatId}`);
  }

  return {
    messageId: "push",
    chatId,
  };
}

/**
 * Push a Flex Message to a user/group
 */
export async function pushFlexMessage(
  to: string,
  altText: string,
  contents: FlexContainer,
  opts: { channelAccessToken?: string; accountId?: string; verbose?: boolean } = {},
): Promise<LineSendResult> {
  const cfg = loadConfig();
  const account = resolveLineAccount({
    cfg,
    accountId: opts.accountId,
  });
  const token = resolveToken(opts.channelAccessToken, account);
  const chatId = normalizeTarget(to);

  const client = new messagingApi.MessagingApiClient({
    channelAccessToken: token,
  });

  const flexMessage: FlexMessage = {
    type: "flex",
    altText: altText.slice(0, 400), // LINE limit
    contents,
  };

  await client
    .pushMessage({
      to: chatId,
      messages: [flexMessage],
    })
    .catch((err) => {
      logLineHttpError(err, "push flex message");
      throw err;
    });

  recordChannelActivity({
    channel: "line",
    accountId: account.accountId,
    direction: "outbound",
  });

  if (opts.verbose) {
    logVerbose(`line: pushed flex message to ${chatId}`);
  }

  return {
    messageId: "push",
    chatId,
  };
}

/**
 * Push a Template Message to a user/group
 */
export async function pushTemplateMessage(
  to: string,
  template: TemplateMessage,
  opts: { channelAccessToken?: string; accountId?: string; verbose?: boolean } = {},
): Promise<LineSendResult> {
  const cfg = loadConfig();
  const account = resolveLineAccount({
    cfg,
    accountId: opts.accountId,
  });
  const token = resolveToken(opts.channelAccessToken, account);
  const chatId = normalizeTarget(to);

  const client = new messagingApi.MessagingApiClient({
    channelAccessToken: token,
  });

  await client.pushMessage({
    to: chatId,
    messages: [template],
  });

  recordChannelActivity({
    channel: "line",
    accountId: account.accountId,
    direction: "outbound",
  });

  if (opts.verbose) {
    logVerbose(`line: pushed template message to ${chatId}`);
  }

  return {
    messageId: "push",
    chatId,
  };
}

/**
 * Push a text message with quick reply buttons
 */
export async function pushTextMessageWithQuickReplies(
  to: string,
  text: string,
  quickReplyLabels: string[],
  opts: { channelAccessToken?: string; accountId?: string; verbose?: boolean } = {},
): Promise<LineSendResult> {
  const cfg = loadConfig();
  const account = resolveLineAccount({
    cfg,
    accountId: opts.accountId,
  });
  const token = resolveToken(opts.channelAccessToken, account);
  const chatId = normalizeTarget(to);

  const client = new messagingApi.MessagingApiClient({
    channelAccessToken: token,
  });

  const message = createTextMessageWithQuickReplies(text, quickReplyLabels);

  await client.pushMessage({
    to: chatId,
    messages: [message],
  });

  recordChannelActivity({
    channel: "line",
    accountId: account.accountId,
    direction: "outbound",
  });

  if (opts.verbose) {
    logVerbose(`line: pushed message with quick replies to ${chatId}`);
  }

  return {
    messageId: "push",
    chatId,
  };
}

/**
 * Create quick reply buttons to attach to a message
 */
export function createQuickReplyItems(labels: string[]): QuickReply {
  const items: QuickReplyItem[] = labels.slice(0, 13).map((label) => ({
    type: "action",
    action: {
      type: "message",
      label: label.slice(0, 20), // LINE limit: 20 chars
      text: label,
    },
  }));
  return { items };
}

/**
 * Create a text message with quick reply buttons
 */
export function createTextMessageWithQuickReplies(
  text: string,
  quickReplyLabels: string[],
): TextMessage & { quickReply: QuickReply } {
  return {
    type: "text",
    text,
    quickReply: createQuickReplyItems(quickReplyLabels),
  };
}

/**
 * Show loading animation to user (lasts up to 20 seconds or until next message)
 */
export async function showLoadingAnimation(
  chatId: string,
  opts: { channelAccessToken?: string; accountId?: string; loadingSeconds?: number } = {},
): Promise<void> {
  const cfg = loadConfig();
  const account = resolveLineAccount({
    cfg,
    accountId: opts.accountId,
  });
  const token = resolveToken(opts.channelAccessToken, account);

  const client = new messagingApi.MessagingApiClient({
    channelAccessToken: token,
  });

  try {
    await client.showLoadingAnimation({
      chatId: normalizeTarget(chatId),
      loadingSeconds: opts.loadingSeconds ?? 20,
    });
    logVerbose(`line: showing loading animation to ${chatId}`);
  } catch (err) {
    // Loading animation may fail for groups or unsupported clients - ignore
    logVerbose(`line: loading animation failed (non-fatal): ${String(err)}`);
  }
}

/**
 * Fetch user profile (display name, picture URL)
 */
export async function getUserProfile(
  userId: string,
  opts: { channelAccessToken?: string; accountId?: string; useCache?: boolean } = {},
): Promise<{ displayName: string; pictureUrl?: string } | null> {
  const useCache = opts.useCache ?? true;

  // Check cache first
  if (useCache) {
    const cached = userProfileCache.get(userId);
    if (cached && Date.now() - cached.fetchedAt < PROFILE_CACHE_TTL_MS) {
      return { displayName: cached.displayName, pictureUrl: cached.pictureUrl };
    }
  }

  const cfg = loadConfig();
  const account = resolveLineAccount({
    cfg,
    accountId: opts.accountId,
  });
  const token = resolveToken(opts.channelAccessToken, account);

  const client = new messagingApi.MessagingApiClient({
    channelAccessToken: token,
  });

  try {
    const profile = await client.getProfile(userId);
    const result = {
      displayName: profile.displayName,
      pictureUrl: profile.pictureUrl,
    };

    // Cache the result
    userProfileCache.set(userId, {
      ...result,
      fetchedAt: Date.now(),
    });

    return result;
  } catch (err) {
    logVerbose(`line: failed to fetch profile for ${userId}: ${String(err)}`);
    return null;
  }
}

/**
 * Get user's display name (with fallback to userId)
 */
export async function getUserDisplayName(
  userId: string,
  opts: { channelAccessToken?: string; accountId?: string } = {},
): Promise<string> {
  const profile = await getUserProfile(userId, opts);
  return profile?.displayName ?? userId;
}