const express = require('express');
const sql = require('mssql');
const cors = require('cors');
const fs = require('fs');
const path = require('path');
const pdfParse = require('pdf-parse'); // For PDF text extraction

const app = express();
const pool = new sql.ConnectionPool({
    server: '192.168.13.30',
    database: 'ocr',
    user: 'sa',
    password: 'sa@12345',
    options: {
        encrypt: false,
        trustServerCertificate: true,
    },
    pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000,
    },
    requestTimeout: 50000,
});
app.use(cors());
app.use(express.json());

// Utility: Get the relative file path
const getRelativePath = (fullPath) => {
    const basePath = '\\\\192.168.13.30\\c$\\GGN Office Repository\\';
    return fullPath.startsWith(basePath)
        ? fullPath.slice(basePath.length).replace(/\\/g, '/')
        : fullPath.replace(/\\/g, '/');
};

// Helper Function: Extract keyword matches with page numbers
const extractKeywordMatches = async (pdfPath, keyword) => {
    try {
        // Read the PDF file from the filesystem
        const dataBuffer = fs.readFileSync(pdfPath);
        const pdfData = await pdfParse(dataBuffer);

        const matches = [];
        const pages = pdfData.text.split('\n\n'); // Each page text is separated by '\n\n'

        // Loop through pages and find keyword matches
        for (let pageIndex = 0; pageIndex < pages.length; pageIndex++) {
            const pageText = pages[pageIndex];
            if (pageText.toLowerCase().includes(keyword.toLowerCase())) {
                matches.push({
                    page: pageIndex + 1, // Page number (1-based index)
                    positions: [] // Placeholder if needed for positions in the future
                });
            }
        }

        return matches;
    } catch (error) {
        console.error('Error extracting keyword matches:', error);
        return [];
    }
};

// Endpoint: Search for PDFs by keywords
app.get('/search', async (req, res) => {
    const { keyword, exclude } = req.query;
    if (!keyword || keyword.trim() === '') {
        return res.status(400).json({ error: 'No search keyword provided.' });
    }

    try {
        await pool.connect();
        const request = pool.request();

        // Construct the SQL query to search for keyword
        let query = 'SELECT Filename FROM files WHERE PdfData LIKE @keyword';
        request.input('keyword', sql.NVarChar, `%${keyword}%`);

        // Exclude words if provided
        if (exclude && exclude.trim() !== '') {
            const excludedWords = exclude.split(/\s+/).filter(Boolean);
            excludedWords.forEach((word, index) => {
                query += ` AND PdfData NOT LIKE @exclude${index}`;
                request.input(`exclude${index}`, sql.NVarChar, `%${word}%`);
            });
        }

        const result = await request.query(query);

        const responseData = [];
        for (const record of result.recordset) {
            const fullPath = record.Filename;
            const relativePath = getRelativePath(fullPath);
            const absolutePath = path.join('\\\\192.168.13.30\\c$\\GGN Office Repository', relativePath);

            // Extract keyword matches and page numbers from the PDF
            const matches = await extractKeywordMatches(absolutePath, keyword);

            responseData.push({
                Filename: fullPath,
                relativePath,
                matches
            });
        }

        res.json(responseData);
    } catch (error) {
        console.error('Error processing search:', error.message);
        res.status(500).json({ error: 'An error occurred while processing your search.' });
    }
});

// Endpoint: Serve PDF files
app.get('/files/*', (req, res) => {
    const relativePath = req.params[0];
    const basePath = '\\\\192.168.13.30\\c$\\GGN Office Repository';
    const filePath = path.join(basePath, relativePath);

    try {
        fs.accessSync(filePath, fs.constants.R_OK);
        res.sendFile(filePath);
    } catch (err) {
        res.status(404).json({ error: 'File not found or inaccessible' });
    }
});

// Run the server
const PORT = process.env.PORT || 3006;
app.listen(PORT, '192.168.7.103', () => {
    console.log(`Server running on http://192.168.7.103:${PORT}`);
});   thia api endpoint is giving me  [
    {
        "Filename": "\\\\192.168.13.30\\c$\\GGN Office Repository\\19(4), arbitration act - Admissibility, relevancy, materiality\\Petition to Special leave to Appeal_8136_2022 - Order_11-Jul-2022.pdf",
        "relativePath": "19(4), arbitration act - Admissibility, relevancy, materiality/Petition to Special leave to Appeal_8136_2022 - Order_11-Jul-2022.pdf",
        "matches": [
            {
                "page": 4,
                "positions": []
            }
        ]
    },
    {
        "Filename": "\\\\192.168.13.30\\c$\\GGN Office Repository\\Arbitrator cannot adjudicate FEMA\\10. Banyan_Tree_Growth_Capital_LLC_vs_Axiom_Cordages_LMH202007052018105990COM749303.pdf",
        "relativePath": "Arbitrator cannot adjudicate FEMA/10. Banyan_Tree_Growth_Capital_LLC_vs_Axiom_Cordages_LMH202007052018105990COM749303.pdf",
        "matches": [
            {
                "page": 2,
                "positions": []
            }
        ]
    },
    {
        "Filename": "\\\\192.168.13.30\\c$\\GGN Office Repository\\Change in Law\\CHANGE IN LAW 2022\\Legal Updated COVID & FM, CHANGE IN LAW\\March 2020 to May 2021- COVID, FMJ, Change in Law Judgments\\7. September 2020\\CRSC_Research_and_Design_Institute_Group_Co_Ltd_vsDE202007102017305529COM651634.pdf",
        "relativePath": "Change in Law/CHANGE IN LAW 2022/Legal Updated COVID & FM, CHANGE IN LAW/March 2020 to May 2021- COVID, FMJ, Change in Law Judgments/7. September 2020/CRSC_Research_and_Design_Institute_Group_Co_Ltd_vsDE202007102017305529COM651634.pdf",
        "matches": [
            {
                "page": 2,
                "positions": []
            }
        ]
    },
    {
        "Filename": "\\\\192.168.13.30\\c$\\GGN Office Repository\\Change in Law - Same economic and legal position\\03. Sion_Panvel vs State of MH.pdf",
        "relativePa   this type of data ...i just want this page no to be diaplyed aftetr the filename in the frontend and when we open any of the pages navigte to that page no ....means that page where the keyowrd appread at fisrt  provifng home.js import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import Navbar from '../components/Navbar';
import Footer from '../components/Footer';
import { useSearchContext } from '../context/searchcontext';
import './Home.css';

const Home = () => {
    const navigate = useNavigate();
    const { searchResults, setSearchResults, addToSearchHistory } = useSearchContext();
    
    const [searchTerm, setSearchTerm] = useState('');
    const [excludeWords, setExcludeWords] = useState('');
    const [error, setError] = useState(null);
    const [isLoading, setIsLoading] = useState(false);
    const [isLoggedIn, setIsLoggedIn] = useState(false);
    const [selectedPdf, setSelectedPdf] = useState(null);

    useEffect(() => {
        const token = localStorage.getItem('token');
        setIsLoggedIn(!!token);
    }, []);

    const handleSearchTermChange = (event) => {
        setSearchTerm(event.target.value);
    };

    const handleExcludeWordsChange = (event) => {
        setExcludeWords(event.target.value);
    };

    const handleSubmit = async (event) => {
        event.preventDefault();
        setIsLoading(true);
        setError(null);
    
        try {
            const response = await fetch(
                `http://192.168.7.103:3006/search?keyword=${encodeURIComponent(searchTerm)}&exclude=${encodeURIComponent(excludeWords || '')}`
            );
            
            if (!response.ok) {
                throw new Error(`Network response was not ok: ${response.status}`);
            }
    
            const data = await response.json();
            setSearchResults(data);
            setError(null);
            addToSearchHistory(searchTerm, data.length);
        } catch (error) {
            console.error('Error fetching search results:', error);
            setError(`Failed to fetch search results: ${error.message}`);
        } finally {
            setIsLoading(false);
        }
    };

    const handlePdfView = (pdf) => {
        setSelectedPdf({
            url: `http://192.168.7.103:3006/files/${encodeURIComponent(pdf.relativePath)}`,
            searchTerm: pdf.searchTerm
        });
    };
    // const handlePdfView = (pdf) => {
    //     const relativePath = getRelativePath(pdf.Filename);
    //     const pdfUrl = `http://192.168.13.30/c/GGN Office Repository/${encodeURIComponent(relativePath)}`;
    //     navigate('/pdf-viewer', { state: { pdfUrl, searchTerm } });
    // };
    
    // const handlePdfView = (pdf) => {
    //     // Correct the relative path to ensure it works
    //     const relativePath = encodeURIComponent(pdf.relativePath); // Use the relativePath provided
    //     const pdfUrl = `http://192.168.7.206:3006/files/${relativePath}`; // Build the correct URL
        
    //     // Navigate to the PDF viewer page with the URL and search term
    //     navigate('/pdf-viewer', { 
    //         state: { 
    //             pdfUrl, 
    //             searchTerm: pdf.searchTerm 
    //         } 
    //     });
    // };
    
    const handleAddToLibrary = async (pdf) => {
        const token = localStorage.getItem('token');
        if (!token) {
            navigate('/login', { 
                state: { 
                    message: 'Please log in to add documents to your library',
                    redirectAfterLogin: '/home'
                } 
            });
            return;
        }

        try {
            const response = await fetch('http://192.168.7.103:3006/api/lib/library/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({ 
                    filename: pdf.relativePath,
                    originalFilePath: pdf.Filename
                })
            });
        
            if (response.ok) {
                alert('Document added to library');
            } else {
                const errorData = await response.json();
                alert(errorData.message || 'Failed to add document');
            }
        } catch (error) {
            console.error('Error adding to library:', error);
            alert('Network error. Please try again.');
        }
    };
    const getRelativePath = (fullPath) => {
        const basePath = '\\\\192.168.13.30\\c$\\GGN Office Repository\\';
        if (fullPath.startsWith(basePath)) {
            return fullPath.slice(basePath.length).replace(/\\/g, '/');
        }
        return fullPath.replace(/\\/g, '/');
    };

    return (
        <div className="app-container">
        <Navbar />
        <main>
            {/* <div className="container">
                <div id="ball"></div>
                <p id="xyz">S&A Law Offices</p>
            </div> */}
            <form onSubmit={handleSubmit}>
                <div className="search-input">
                    <input
                        type="text"
                        placeholder="Enter text"
                        value={searchTerm}
                        onChange={handleSearchTermChange}
                        required
                    />
                    <input
                        type="text"
                        placeholder="Exclude these words (Optional)"
                        value={excludeWords}
                        onChange={handleExcludeWordsChange}
                    />
                    <button type="submit">Search</button>
                </div>
            </form>
            
            {isLoading && <p>Searching...</p>}
            {error && <p style={{ color: 'red' }}>{error}</p>}
            <br />
            <div>
                {searchResults.length > 0 ? (
                    <div className="scrollable-container">
                        <p>{searchResults.length} document(s) found:</p>
                        <ul style={{ listStyleType: 'none', padding: 0 }}>
                            {searchResults.map((result, index) => {
                                const relativePath = getRelativePath(result.Filename);
                                const encodedPath = encodeURI(relativePath);

                                return (
                                    <li key={index} style={{ margin: '5px 0', position: 'relative' }}>
                                        <a 
                                            href={`http://192.168.7.103:3006/files/${encodedPath}`} 
                                            target="_blank" 
                                            rel="noopener noreferrer"
                                            style={{ color: 'blue', textDecoration: 'underline' }}
                                        >
                                            {relativePath}
                                        </a> 

                                        <span 
                                            className="add-to-library" 
                                            onClick={() => handleAddToLibrary(result)} 
                                            title="Add to Library"
                                            style={{
                                                marginLeft: '10px',
                                                cursor: 'pointer',
                                                color: 'green',
                                                fontSize: '20px',
                                                display: 'inline-block',
                                            }}
                                        >
                                            <button>Add</button>
                                        </span>
                                    </li>
                                )
                            })}
                        </ul>
                        {/* <ul style={{ listStyleType: 'none', padding: 0 }}>
                            {searchResults.map((result, index) => {
                            const relativePath = getRelativePath(result.Filename);
                            return (
                           <li key={index} style={{ margin: '5px 0' }}>
                               <span
                                 onClick={() => handlePdfView(result)}
                                 style={{ color: 'blue', textDecoration: 'underline', cursor: 'pointer' }}
                                 >
                                 {relativePath}
                               </span>
                             <button onClick={() => handleAddToLibrary(result)}>Add</button>
                           </li>
                           );
                           })}
                        </ul> */}

                    </div>
                    ) : (
                        !isLoading && <p>No results found.</p>
                    )}
                </div>
            </main>
            <Footer />
        </div>
    );
};

export default Home;
   also aply a condition in backend that if file is other then pdf dont chck it ...