import { GoogleGenerativeAI } from '@google/generative-ai';
import { GoogleAIFileManager } from '@google/generative-ai/server';
import * as fs from 'fs';
import * as path from 'path';

// .env 로드 (실제 프로젝트 루트 위치에 맞게 조정 필요시 수정)
import * as dotenv from 'dotenv';
dotenv.config({ path: path.join(__dirname, '../.env') });
dotenv.config({ path: path.join(__dirname, '../.env.local') });

// API Key 확인
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
    console.error('❌ 환경 변수 GEMINI_API_KEY가 설정되지 않았습니다.');
    process.exit(1);
}

const genAI = new GoogleGenerativeAI(apiKey);
const fileManager = new GoogleAIFileManager(apiKey);

// Phase 0 테이블 파싱 JSON 스키마 명세
const promptText = `
아래 보험료 표 이미지(또는 PDF 파일)를 분석하여 모든 데이터를 다음 JSON 형식으로 추출해 주세요.
단 하나의 수치도 임의로 추정하거나 생략하지 마세요.

\`\`\`json
{
  "tableType": "premium | surrender_value",
  "headers": { "row": ["연령", "성별", ...], "col": ["납입기간", "보장금액", ...] },
  "data": [
    { 
      "age": 40, 
      "gender": "M", 
      "smokingStatus": "non_smoker",
      "paymentPeriod": 20, 
      "coverageAmount": 100000000, 
      "premium": 234560 
    }
  ],
  "conditions": "조건부 주석 원문 그대로",
  "confidence": "high | medium | low"
}
\`\`\`

출력은 오직 순수한 JSON 문자열만 응답하세요. 백틱(\`\`\`)이나 추가 설명은 일절 포함하지 마세요.
`;

async function runTest(imagePath: string) {
    console.log(`\n🔍 테스트 시작: ${path.basename(imagePath)} 분석 중...`);

    try {
        // 2.5 Flash 모델 인스턴스화
        const model = genAI.getGenerativeModel({ model: "gemini-2.5-flash" });

        // 이미지 및 PDF 파일 준비
        let mimeType = 'image/png';
        if (imagePath.toLowerCase().endsWith('.jpg') || imagePath.toLowerCase().endsWith('.jpeg')) {
            mimeType = 'image/jpeg';
        } else if (imagePath.toLowerCase().endsWith('.webp')) {
            mimeType = 'image/webp';
        } else if (imagePath.toLowerCase().endsWith('.pdf')) {
            mimeType = 'application/pdf';
        }

        console.log('⏳ Gemini File API에 업로드 중...');
        const uploadResponse = await fileManager.uploadFile(imagePath, {
            mimeType,
            displayName: path.basename(imagePath),
        });
        console.log(`✅ 업로드 완료: ${uploadResponse.file.uri} (${uploadResponse.file.name})`);

        console.log('⏳ 문서 처리가 완료되기를 기다립니다...');
        let fileState = await fileManager.getFile(uploadResponse.file.name);
        while (fileState.state === 'PROCESSING') {
            process.stdout.write('.');
            await new Promise((resolve) => setTimeout(resolve, 2000));
            fileState = await fileManager.getFile(uploadResponse.file.name);
        }

        if (fileState.state === 'FAILED') {
            throw new Error('문서 처리 실패!');
        }

        console.log('\n⏳ Gemini 2.5 Flash Vision API 호출 중...');
        const result = await model.generateContent({
            contents: [
                {
                    role: "user",
                    parts: [
                        {
                            fileData: {
                                mimeType: uploadResponse.file.mimeType,
                                fileUri: uploadResponse.file.uri
                            }
                        },
                        { text: promptText }
                    ]
                }
            ],
            generationConfig: {
                responseMimeType: "application/json"
            }
        });

        const response = await result.response;
        let text = response.text();

        // 마크다운 흔적 제거 (만약 포함되었을 경우 방어 코드)
        text = text.replace(/```json/gi, '').replace(/```/g, '').trim();

        console.log('\n✅ [추출 결과]');

        // JSON 파싱 검증
        try {
            const jsonData = JSON.parse(text);
            console.dir(jsonData, { depth: null, colors: true });

            console.log('\n📊 [Summary]');
            console.log(`- 테이블 유형: ${jsonData.tableType}`);
            console.log(`- 가공된 데이터 행 수: ${jsonData.data?.length || 0} 개`);
            console.log(`- 조건/주석: ${jsonData.conditions}`);
            console.log(`- AI 추출 신뢰도: ${jsonData.confidence}`);

        } catch (e) {
            console.error('\n❌ 추출된 텍스트가 유효한 JSON 형식이 아닙니다!');
            console.log('--- 원문 응답 ---');
            console.log(text);
            console.log('-----------------');
        }

    } catch (error) {
        console.error(`\n❌ API 호출 중 에러 발생:`, error);
    }
}

// 스크립트 실행 엔트리포인트
async function main() {
    const args = process.argv.slice(2);
    const sampleImagePath = args[0];

    if (!sampleImagePath) {
        console.log(`
사용법: npx tsx scripts/poc-table-parser.ts <이미지파일_경로>
예시:   npx tsx scripts/poc-table-parser.ts ./samples/life-premium-sample1.png
    `);
        process.exit(1);
    }

    const absolutePath = path.resolve(sampleImagePath);
    if (!fs.existsSync(absolutePath)) {
        console.error(`❌ 파일을 찾을 수 없습니다: ${absolutePath}`);
        process.exit(1);
    }

    await runTest(absolutePath);
}

main();
