// pages/wiki/identify/index.js
import request from '../../../utils/request';

Page({
    data: {
        imagePath: '',
        results: [],
        isLoading: true,
        hasError: false,
        topResult: null
    },

    onLoad(options) {
        // Image path is passed via global data (too long for URL params)
        const app = getApp();
        const imagePath = app.globalData._identifyImagePath || '';

        if (!imagePath) {
            this.setData({ isLoading: false, hasError: true });
            return;
        }

        this.setData({ imagePath });
        this.classifyPlant(imagePath);
    },

    async classifyPlant(filePath) {
        this.setData({ isLoading: true, hasError: false });

        try {
            // Directly upload file to classify endpoint without uploading to MinIO file service
            const res = await request.uploadToUrl('/plant/classify/plant', filePath);

            const results = res.result || [];

            // Map results with percentage scores
            const mappedResults = results.map((item, index) => ({
                index: index,
                name: item.name,
                score: item.score,
                percent: (item.score * 100).toFixed(2),
                description: (item.baike_info && item.baike_info.description) || '',
                baikeUrl: (item.baike_info && item.baike_info.baike_url) || '',
                isTop: index === 0
            }));

            this.setData({
                results: mappedResults,
                topResult: mappedResults.length > 0 ? mappedResults[0] : null,
                isLoading: false
            });
        } catch (err) {
            console.error('Classify failed', err);
            this.setData({ isLoading: false, hasError: true });
        }
    },

    // Retry identification
    handleRetry() {
        if (this.data.imagePath) {
            this.classifyPlant(this.data.imagePath);
        }
    },

    // Go back and re-select image
    handleReselect() {
        wx.navigateBack();
    },

    // Search in wiki
    searchInWiki(e) {
        const name = e.currentTarget.dataset.name;
        // Navigate back to wiki and trigger search
        const pages = getCurrentPages();
        if (pages.length >= 2) {
            const wikiPage = pages[pages.length - 2];
            wikiPage.setData({ searchQuery: name }, () => {
                wikiPage.fetchWikiList(true);
            });
        }
        wx.navigateBack();
    },

    // Preview uploaded image
    previewImage() {
        wx.previewImage({
            urls: [this.data.imagePath],
            current: this.data.imagePath
        });
    }
});
