import os
from werkzeug.utils import secure_filename
from flask import current_app

def allowed_file(filename):
    """Verifica se a extensão do arquivo é permitida"""
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in current_app.config['ALLOWED_EXTENSIONS']

def save_file(file):
    """Salva um arquivo no diretório de uploads"""
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
        file.save(file_path)
        return file_path
    return None

def delete_file(file_path):
    """Remove um arquivo do sistema"""
    try:
        if os.path.exists(file_path):
            os.remove(file_path)
            return True
    except Exception:
        return False
    return False

def read_document_content(file_path, filename):
    """
    Lê o conteúdo de um arquivo, tentando diferentes formatos (texto, PDF, Word, Excel, CSV, JSON).
    Retorna o conteúdo como string.
    """
    file_extension = os.path.splitext(filename)[1].lower()
    content = ""

    try:
        if file_extension == '.txt':
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
        elif file_extension == '.pdf':
            import PyPDF2
            with open(file_path, 'rb') as f:
                reader = PyPDF2.PdfReader(f)
                for page_num in range(len(reader.pages)):
                    content += reader.pages[page_num].extract_text() + "\n"
        elif file_extension in ['.doc', '.docx']:
            import docx
            doc = docx.Document(file_path)
            for para in doc.paragraphs:
                content += para.text + "\n"
        elif file_extension in ['.xls', '.xlsx']:
            import openpyxl
            workbook = openpyxl.load_workbook(file_path)
            for sheet_name in workbook.sheetnames:
                sheet = workbook[sheet_name]
                for row in sheet.iter_rows():
                    row_values = [cell.value for cell in row if cell.value is not None]
                    if row_values:
                        content += "\t".join(map(str, row_values)) + "\n"
        elif file_extension == '.csv':
            import csv
            with open(file_path, 'r', encoding='utf-8') as f:
                reader = csv.reader(f)
                for row in reader:
                    content += ",".join(row) + "\n"
        elif file_extension == '.json':
            import json
            with open(file_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
                content = json.dumps(data, indent=2)
        else:
            try:
                 with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
            except Exception as e:
                 print(f"Erro ao ler arquivo {filename} como texto simples: {e}")
                 content = f"[ERRO: Não foi possível ler o conteúdo do arquivo {filename}]"

    except FileNotFoundError:
        content = f"[ERRO: Arquivo {filename} não encontrado no sistema de arquivos]"
    except Exception as e:
        print(f"Erro ao ler arquivo {filename} ({file_extension}): {e}")
        content = f"[ERRO: Não foi possível ler o conteúdo do arquivo {filename}]"

    return content 