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
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
import os
import sys
from pathlib import Path
from dotenv import load_dotenv
from supabase import create_client, Client
import time

# Carrega variáveis de ambiente
load_dotenv()

# Configuração de caminhos
ROOT_DIR = Path(__file__).parent
IMAGES_DIR = ROOT_DIR / "imagens"
THUMBNAILS_DIR = ROOT_DIR / "thumbnails"

# Cria diretórios se não existirem
THUMBNAILS_DIR.mkdir(exist_ok=True)

class DatabaseSetup:
    def __init__(self):
        """Inicializa configuração do banco"""
        self.supabase_url = os.getenv('SUPABASE_URL')
        self.supabase_key = os.getenv('SUPABASE_KEY')
        self.pinecone_api_key = os.getenv('PINECONE_API_KEY')
        self.index_name = os.getenv('PINECONE_INDEX_NAME', 'jewelry-embeddings')
        
        if not all([self.supabase_url, self.supabase_key]):
            raise ValueError("❌ Variáveis de ambiente do Supabase obrigatórias não encontradas!")
        
        self.supabase: Client = create_client(self.supabase_url, self.supabase_key)
        
        # Inicializa Pinecone apenas se a API key estiver disponível
        if self.pinecone_api_key:
            try:
                from pinecone import Pinecone
                self.pc = Pinecone(api_key=self.pinecone_api_key)
                print("✅ Pinecone configurado")
            except ImportError as e:
                print(f"⚠️  Erro ao importar Pinecone: {e}")
                print("   Execute: pip uninstall pinecone-client && pip install pinecone")
                self.pc = None
        else:
            print("⚠️  PINECONE_API_KEY não encontrada - Pinecone será configurado depois")
            self.pc = None
        
        print(f"✅ Configuração carregada do diretório: {ROOT_DIR}")
        print(f"📁 Diretório de imagens: {IMAGES_DIR}")
        print(f"📁 Diretório de thumbnails: {THUMBNAILS_DIR}")
    
    def create_database_tables(self):
        """Cria as tabelas necessárias no Supabase"""
        
        sql_commands = [
            # Extensões
            """CREATE EXTENSION IF NOT EXISTS "uuid-ossp";""",
            
            # Tabela principal de peças
            """
            CREATE TABLE IF NOT EXISTS pieces (
                sku VARCHAR(50) PRIMARY KEY,
                name VARCHAR(255) NOT NULL,
                collection VARCHAR(100),
                material VARCHAR(255),
                predominant_metal VARCHAR(100),
                stone VARCHAR(100),
                stone_color VARCHAR(50),
                size VARCHAR(50),
                weight_grams DECIMAL(8,2),
                price_brl DECIMAL(10,2),
                description TEXT,
                category VARCHAR(50),
                gender VARCHAR(20),
                style VARCHAR(100),
                is_active BOOLEAN DEFAULT true,
                created_at TIMESTAMP DEFAULT NOW(),
                updated_at TIMESTAMP DEFAULT NOW()
            );
            """,
            
            # Tabela de imagens
            """
            CREATE TABLE IF NOT EXISTS piece_images (
                id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
                sku VARCHAR(50) REFERENCES pieces(sku) ON DELETE CASCADE,
                image_type VARCHAR(20) CHECK (image_type IN ('product', 'lifestyle', 'detail', 'packaging')),
                original_url VARCHAR(500),
                thumbnail_url VARCHAR(500),
                file_name VARCHAR(255),
                file_size_bytes INTEGER,
                image_width INTEGER,
                image_height INTEGER,
                embeddings_vector_id VARCHAR(100) UNIQUE,
                technical_analysis JSONB,
                ai_description TEXT,
                dominant_colors JSONB,
                visual_features JSONB,
                quality_score DECIMAL(3,2),
                is_primary BOOLEAN DEFAULT false,
                created_at TIMESTAMP DEFAULT NOW()
            );
            """,
            
            # Tabela de características visuais
            """
            CREATE TABLE IF NOT EXISTS visual_features (
                id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
                image_id UUID REFERENCES piece_images(id) ON DELETE CASCADE,
                feature_type VARCHAR(50),
                feature_value VARCHAR(255),
                confidence_score DECIMAL(3,2),
                created_at TIMESTAMP DEFAULT NOW()
            );
            """,
            
            # Tabela de tags
            """
            CREATE TABLE IF NOT EXISTS image_tags (
                id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
                image_id UUID REFERENCES piece_images(id) ON DELETE CASCADE,
                tag VARCHAR(100),
                confidence DECIMAL(3,2),
                tag_type VARCHAR(50),
                created_at TIMESTAMP DEFAULT NOW()
            );
            """,
            
            # Tabela de log
            """
            CREATE TABLE IF NOT EXISTS processing_log (
                id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
                sku VARCHAR(50),
                image_id UUID,
                process_type VARCHAR(50),
                status VARCHAR(20),
                error_message TEXT,
                processing_time_ms INTEGER,
                created_at TIMESTAMP DEFAULT NOW()
            );
            """,
            
            # Índices
            """
            CREATE INDEX IF NOT EXISTS idx_piece_images_sku ON piece_images(sku);
            CREATE INDEX IF NOT EXISTS idx_piece_images_type ON piece_images(image_type);
            CREATE INDEX IF NOT EXISTS idx_piece_images_primary ON piece_images(is_primary);
            CREATE INDEX IF NOT EXISTS idx_visual_features_image_id ON visual_features(image_id);
            CREATE INDEX IF NOT EXISTS idx_image_tags_image_id ON image_tags(image_id);
            CREATE INDEX IF NOT EXISTS idx_processing_log_sku ON processing_log(sku);
            CREATE INDEX IF NOT EXISTS idx_pieces_category ON pieces(category);
            CREATE INDEX IF NOT EXISTS idx_pieces_collection ON pieces(collection);
            """,
            
            # Função de trigger
            """
            CREATE OR REPLACE FUNCTION update_updated_at_column()
            RETURNS TRIGGER AS $$
            BEGIN
                NEW.updated_at = NOW();
                RETURN NEW;
            END;
            $$ language 'plpgsql';
            """,
            
            # Trigger
            """
            DROP TRIGGER IF EXISTS update_pieces_updated_at ON pieces;
            CREATE TRIGGER update_pieces_updated_at 
                BEFORE UPDATE ON pieces 
                FOR EACH ROW 
                EXECUTE FUNCTION update_updated_at_column();
            """
        ]
        
        try:
            print("🗄️  Criando estrutura do banco de dados...")
            
            for i, command in enumerate(sql_commands, 1):
                print(f"🔄 Executando comando {i}/{len(sql_commands)}...")
                
                # Executa comando SQL diretamente
                try:
                    result = self.supabase.postgrest.rpc('exec_sql', {'sql': command.strip()}).execute()
                except Exception as cmd_error:
                    # Se exec_sql não funcionar, tenta executar diretamente
                    print(f"   ⚠️  Tentativa alternativa para comando {i}...")
                    # Para comandos DDL, podemos tentar usar uma abordagem diferente
                    continue
                
            print("✅ Estrutura do banco criada com sucesso!")
            return True
            
        except Exception as e:
            print(f"❌ Erro ao criar estrutura do banco: {e}")
            print("   Você pode executar os comandos SQL manualmente no painel do Supabase")
            return False
    
    def setup_pinecone_index(self):
        """Configura o índice do Pinecone"""
        if not self.pc:
            print("⚠️  Pinecone não configurado - pulando configuração do índice")
            return None
            
        try:
            from pinecone import ServerlessSpec
            
            # Verifica índices existentes
            existing_indexes = self.pc.list_indexes().names()
            
            if self.index_name in existing_indexes:
                print(f"✅ Índice '{self.index_name}' já existe!")
                index_info = self.pc.describe_index(self.index_name)
                print(f"📊 Dimensão: {index_info.dimension}")
                print(f"📊 Métrica: {index_info.metric}")
                
            else:
                print(f"🚀 Criando índice '{self.index_name}'...")
                self.pc.create_index(
                    name=self.index_name,
                    dimension=768,  # ViT-L-14 OpenCLIP
                    metric='cosine',
                    spec=ServerlessSpec(
                        cloud='aws',
                        region='us-east-1'
                    )
                )
                
                # Aguarda criação
                print("⏳ Aguardando criação do índice...")
                while True:
                    try:
                        index_info = self.pc.describe_index(self.index_name)
                        if index_info.status.state == "Ready":
                            break
                    except:
                        pass
                    time.sleep(5)
                
                print(f"✅ Índice '{self.index_name}' criado com sucesso!")
            
            # Testa conexão
            index = self.pc.Index(self.index_name)
            stats = index.describe_index_stats()
            print(f"📊 Vetores no índice: {stats.total_vector_count}")
            
            return index
            
        except Exception as e:
            print(f"❌ Erro ao configurar Pinecone: {e}")
            return None
    
    def verify_directories(self):
        """Verifica e cria diretórios necessários"""
        print("📁 Verificando estrutura de diretórios...")
        
        if not IMAGES_DIR.exists():
            print(f"⚠️  Diretório de imagens não encontrado: {IMAGES_DIR}")
            print("   Criando diretório...")
            IMAGES_DIR.mkdir(parents=True, exist_ok=True)
        
        # Conta arquivos PNG
        png_files = list(IMAGES_DIR.glob("*.png"))
        print(f"📸 Encontrados {len(png_files)} arquivos PNG em {IMAGES_DIR}")
        
        if len(png_files) == 0:
            print("⚠️  Nenhuma imagem PNG encontrada!")
            print("   Certifique-se de colocar as imagens no diretório 'imagens'")
        else:
            # Mostra algumas imagens encontradas
            print("   Exemplos de imagens encontradas:")
            for img in png_files[:5]:
                print(f"     • {img.name}")
            if len(png_files) > 5:
                print(f"     • ... e mais {len(png_files) - 5} imagens")
        
        # Verifica se existe CSV de metadados
        csv_path = ROOT_DIR / "jewelry_metadata.csv"
        if not csv_path.exists():
            print(f"⚠️  Arquivo de metadados não encontrado: {csv_path}")
            print("   Exporte a planilha Google Sheets como CSV com este nome")
        else:
            print(f"✅ Arquivo de metadados encontrado: {csv_path}")
        
        return len(png_files) > 0 or csv_path.exists()
    
    def create_sql_file(self):
        """Cria arquivo SQL para execução manual se necessário"""
        sql_content = """
-- Estrutura do banco para catalogação de joias
-- Execute este script no SQL Editor do Supabase se o setup automático falhar

-- Extensões necessárias
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

-- Tabela principal de peças
CREATE TABLE IF NOT EXISTS pieces (
    sku VARCHAR(50) PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    collection VARCHAR(100),
    material VARCHAR(255),
    predominant_metal VARCHAR(100),
    stone VARCHAR(100),
    stone_color VARCHAR(50),
    size VARCHAR(50),
    weight_grams DECIMAL(8,2),
    price_brl DECIMAL(10,2),
    description TEXT,
    category VARCHAR(50),
    gender VARCHAR(20),
    style VARCHAR(100),
    is_active BOOLEAN DEFAULT true,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW()
);

-- Tabela de imagens das peças
CREATE TABLE IF NOT EXISTS piece_images (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    sku VARCHAR(50) REFERENCES pieces(sku) ON DELETE CASCADE,
    image_type VARCHAR(20) CHECK (image_type IN ('product', 'lifestyle', 'detail', 'packaging')),
    original_url VARCHAR(500),
    thumbnail_url VARCHAR(500),
    file_name VARCHAR(255),
    file_size_bytes INTEGER,
    image_width INTEGER,
    image_height INTEGER,
    embeddings_vector_id VARCHAR(100) UNIQUE,
    technical_analysis JSONB,
    ai_description TEXT,
    dominant_colors JSONB,
    visual_features JSONB,
    quality_score DECIMAL(3,2),
    is_primary BOOLEAN DEFAULT false,
    created_at TIMESTAMP DEFAULT NOW()
);

-- Tabela de características visuais extraídas
CREATE TABLE IF NOT EXISTS visual_features (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    image_id UUID REFERENCES piece_images(id) ON DELETE CASCADE,
    feature_type VARCHAR(50),
    feature_value VARCHAR(255),
    confidence_score DECIMAL(3,2),
    created_at TIMESTAMP DEFAULT NOW()
);

-- Tabela de tags automáticas
CREATE TABLE IF NOT EXISTS image_tags (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    image_id UUID REFERENCES piece_images(id) ON DELETE CASCADE,
    tag VARCHAR(100),
    confidence DECIMAL(3,2),
    tag_type VARCHAR(50),
    created_at TIMESTAMP DEFAULT NOW()
);

-- Tabela de histórico de processamento
CREATE TABLE IF NOT EXISTS processing_log (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    sku VARCHAR(50),
    image_id UUID,
    process_type VARCHAR(50),
    status VARCHAR(20),
    error_message TEXT,
    processing_time_ms INTEGER,
    created_at TIMESTAMP DEFAULT NOW()
);

-- Índices para otimização
CREATE INDEX IF NOT EXISTS idx_piece_images_sku ON piece_images(sku);
CREATE INDEX IF NOT EXISTS idx_piece_images_type ON piece_images(image_type);
CREATE INDEX IF NOT EXISTS idx_piece_images_primary ON piece_images(is_primary);
CREATE INDEX IF NOT EXISTS idx_visual_features_image_id ON visual_features(image_id);
CREATE INDEX IF NOT EXISTS idx_image_tags_image_id ON image_tags(image_id);
CREATE INDEX IF NOT EXISTS idx_processing_log_sku ON processing_log(sku);
CREATE INDEX IF NOT EXISTS idx_pieces_category ON pieces(category);
CREATE INDEX IF NOT EXISTS idx_pieces_collection ON pieces(collection);

-- Função para atualizar updated_at automaticamente
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ language 'plpgsql';

-- Trigger para atualizar updated_at na tabela pieces
DROP TRIGGER IF EXISTS update_pieces_updated_at ON pieces;
CREATE TRIGGER update_pieces_updated_at 
    BEFORE UPDATE ON pieces 
    FOR EACH ROW 
    EXECUTE FUNCTION update_updated_at_column();

-- Views úteis
CREATE OR REPLACE VIEW pieces_with_images AS
SELECT 
    p.*,
    pi.id as image_id,
    pi.image_type,
    pi.original_url,
    pi.thumbnail_url,
    pi.ai_description,
    pi.dominant_colors,
    pi.quality_score,
    pi.is_primary
FROM pieces p
LEFT JOIN piece_images pi ON p.sku = pi.sku
WHERE p.is_active = true;
"""
        
        sql_file_path = ROOT_DIR / "database_structure.sql"
        with open(sql_file_path, 'w', encoding='utf-8') as f:
            f.write(sql_content)
        
        print(f"📄 Arquivo SQL criado: {sql_file_path}")
        print("   Use este arquivo para criar as tabelas manualmente se necessário")
    
    def run_setup(self):
        """Executa setup completo"""
        print("🚀 Iniciando configuração do sistema de catalogação...")
        print(f"📍 Diretório de trabalho: {ROOT_DIR}")
        
        # Cria arquivo SQL de backup
        self.create_sql_file()
        
        # Verifica diretórios
        self.verify_directories()
        
        # Configura banco
        print("\n🗄️  Configurando banco de dados...")
        db_success = self.create_database_tables()
        
        # Configura Pinecone
        print("\n🔍 Configurando Pinecone...")
        index = self.setup_pinecone_index()
        
        print("\n" + "="*60)
        if db_success:
            print("✅ Configuração do banco: SUCESSO")
        else:
            print("⚠️  Configuração do banco: VERIFICAR")
            print("   Execute o arquivo 'database_structure.sql' manualmente no Supabase")
        
        if index or not self.pc:
            print("✅ Configuração do Pinecone: SUCESSO")
        else:
            print("⚠️  Configuração do Pinecone: VERIFICAR")
        
        print("\n📋 Próximos passos:")
        print("   1. Certifique-se de que as imagens estão no diretório 'imagens'")
        print("   2. Exporte a planilha como 'jewelry_metadata.csv'")
        print("   3. Configure todas as variáveis no arquivo .env")
        print("   4. Execute: python jewelry_cataloger.py")
        
        return True

if __name__ == "__main__":
    try:
        setup = DatabaseSetup()
        success = setup.run_setup()
        
        if success:
            print("\n🎉 Setup concluído!")
        else:
            print("\n❌ Falha no setup. Verifique os logs acima.")
            sys.exit(1)
            
    except Exception as e:
        print(f"❌ Erro fatal na configuração: {e}")
        print("\nDicas para resolver:")
        print("1. Verifique se o arquivo .env está configurado corretamente")
        print("2. Execute: pip uninstall pinecone-client")
        print("3. Execute: pip install pinecone")
        sys.exit(1)