File size: 3,207 Bytes
97b638a
55ffa7e
 
 
a6145bc
97b638a
 
a6145bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97b638a
a6145bc
 
97b638a
 
 
 
 
 
 
a6145bc
 
 
 
 
 
 
97b638a
a6145bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97b638a
 
 
a6145bc
 
 
 
97b638a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const env = require('../config/env');
// Bucket administration needs the service role; a user's own client cannot
// list or create buckets.
const { supabaseServiceRole: supabaseAdmin } = require('../config/supabase');
const { uploadToStorage } = require('../services/storage.service');
const { success, error, serverError } = require('../utils/response');

const AI_SCAN_BUCKET = 'flora-scans';

async function ensureAiScanBucket() {
  const { data: buckets, error: bucketsError } = await supabaseAdmin.storage.listBuckets();
  if (bucketsError) {
    throw new Error(`Failed to inspect storage buckets: ${bucketsError.message}`);
  }

  if (buckets.some((bucket) => bucket.id === AI_SCAN_BUCKET)) {
    return;
  }

  const { error: createError } = await supabaseAdmin.storage.createBucket(AI_SCAN_BUCKET, {
    public: true,
    fileSizeLimit: env.maxFileSizeMb * 1024 * 1024,
    allowedMimeTypes: ['image/jpeg', 'image/png', 'image/webp', 'image/gif'],
  });

  if (createError) {
    throw new Error(`Failed to create ${AI_SCAN_BUCKET} bucket: ${createError.message}`);
  }
}

/**
 * POST /api/ai/identify — upload an image to storage and forward the public URL
 * (or a text query) to the shared n8n plant-detect workflow.
 */
async function identifyPlant(req, res) {
  try {
    if (!env.n8nWebhookUrl) {
      return error(res, 'AI identification service is not configured yet', 503, 'SERVICE_UNAVAILABLE');
    }

    const type = req.body?.type === 'text' ? 'text' : 'image';
    let payload;

    if (type === 'image') {
      if (!req.file) {
        return error(res, 'Image file is required', 400);
      }

      await ensureAiScanBucket();

      const imageUrl = await uploadToStorage(
        AI_SCAN_BUCKET,
        req.file.buffer,
        req.file.originalname,
        req.file.mimetype,
      );

      payload = {
        type: 'image',
        input: imageUrl,
      };
    } else {
      const input = typeof req.body?.input === 'string' ? req.body.input.trim() : '';
      if (input.length < 2) {
        return error(res, 'Plant name is required', 400);
      }

      payload = {
        type: 'text',
        input,
      };
    }

    const response = await fetch(env.n8nWebhookUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(payload),
    });

    if (!response.ok) {
      const text = await response.text();
      console.error('n8n webhook error:', text);
      return error(res, 'AI service returned an error', 502, 'BAD_GATEWAY');
    }

    const aiResult = await response.json();

    return success(res, {
      identification: aiResult,
      message: 'Plant identified successfully',
    });
  } catch (err) {
    console.error('identifyPlant error:', err);
    return serverError(res, 'AI identification service failed');
  }
}

/**
 * GET /api/ai/status — check if AI service is available
 */
async function aiStatus(req, res) {
  return success(res, {
    available: !!env.n8nWebhookUrl,
    message: env.n8nWebhookUrl
      ? 'AI identification service is online'
      : 'AI identification service is not configured yet',
  });
}

module.exports = { identifyPlant, aiStatus };