#!/usr/bin/env python3
"""
Анализ финансовых и конфиденциальных данных из таблиц i21
"""
import csv
import json
from pathlib import Path
from collections import defaultdict, Counter
import re

DUMPS_DIR = Path('/root/dumps/50.21.183.111')

print("=" * 80)
print("АНАЛИЗ ФИНАНСОВЫХ И КОНФИДЕНЦИАЛЬНЫХ ДАННЫХ")
print("=" * 80)

def read_dat_file(filepath, skip_header=True):
    """Читает .dat файл, пропуская заголовок SQL Server"""
    rows = []
    try:
        with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
            lines = f.readlines()
        
        # Пропускаем первые 3 строки (заголовок SQL Server + разделитель)
        start_idx = 3 if skip_header and len(lines) > 3 else 0
        
        for line in lines[start_idx:]:
            if '|' in line and not line.startswith('---'):
                parts = line.strip().split('|')
                if parts:
                    rows.append(parts)
    except Exception as e:
        print(f"Ошибка чтения {filepath}: {e}")
    return rows

# Анализ всех БД
all_dbs = [d for d in DUMPS_DIR.iterdir() if d.is_dir()]

print(f"\nВсего баз данных: {len(all_dbs)}")

# Структура анализа
analysis = {
    'employees': [],  # tblPREmployee
    'entities': [],   # tblEMEntity
    'gl_transactions': [],  # tblGLDetail
    'invoices': [],   # tblARInvoice
    'bills': [],      # tblAPBill
}

# Анализ каждой БД
for db_dir in all_dbs:
    db_name = db_dir.name
    print(f"\n[Анализ] {db_name}")
    
    # Сотрудники
    emp_file = db_dir / 'dbo_tblPREmployee.dat'
    if emp_file.exists():
        rows = read_dat_file(emp_file)
        print(f"  - Сотрудники: {len(rows)} записей")
        analysis['employees'].extend([(db_name, r) for r in rows[:100]])
    
    # Entities (клиенты/поставщики)
    entity_file = db_dir / 'dbo_tblEMEntity.dat'
    if entity_file.exists():
        rows = read_dat_file(entity_file)
        print(f"  - Entities: {len(rows)} записей")
        analysis['entities'].extend([(db_name, r) for r in rows[:100]])
    
    # GL транзакции
    gl_file = db_dir / 'dbo_tblGLDetail.dat'
    if gl_file.exists():
        rows = read_dat_file(gl_file)
        print(f"  - GL транзакции: {len(rows)} записей")
        analysis['gl_transactions'].extend([(db_name, r) for r in rows[:100]])
    
    # Инвойсы
    inv_file = db_dir / 'dbo_tblARInvoice.dat'
    if inv_file.exists():
        rows = read_dat_file(inv_file)
        print(f"  - Инвойсы: {len(rows)} записей")
        analysis['invoices'].extend([(db_name, r) for r in rows[:100]])
    
    # Счета
    bill_file = db_dir / 'dbo_tblAPBill.dat'
    if bill_file.exists():
        rows = read_dat_file(bill_file)
        print(f"  - Счета: {len(rows)} записей")
        analysis['bills'].extend([(db_name, r) for r in rows[:100]])

# Вывод образцов данных
print("\n" + "=" * 80)
print("ОБРАЗЦЫ ДАННЫХ")
print("=" * 80)

if analysis['employees']:
    print(f"\n[СОТРУДНИКИ] Примеры (всего {len(analysis['employees'])}):")
    print("-" * 80)
    for db, row in analysis['employees'][:5]:
        print(f"\nБаза: {db}")
        print(f"Данные: {' | '.join(row[:15])}")

if analysis['entities']:
    print(f"\n[ENTITIES] Примеры (всего {len(analysis['entities'])}):")
    print("-" * 80)
    for db, row in analysis['entities'][:5]:
        print(f"\nБаза: {db}")
        print(f"Данные: {' | '.join(row[:15])}")

if analysis['gl_transactions']:
    print(f"\n[GL ТРАНЗАКЦИИ] Примеры (всего {len(analysis['gl_transactions'])}):")
    print("-" * 80)
    for db, row in analysis['gl_transactions'][:5]:
        print(f"\nБаза: {db}")
        print(f"Данные: {' | '.join(row[:15])}")

print("\n" + "=" * 80)
print("ВЫВОДЫ")
print("=" * 80)

# Подсчет статистики
print(f"\nВсего записей:")
print(f"  - Сотрудники: {len(analysis['employees'])}")
print(f"  - Entities: {len(analysis['entities'])}")
print(f"  - GL транзакции: {len(analysis['gl_transactions'])}")
print(f"  - Инвойсы: {len(analysis['invoices'])}")
print(f"  - Счета: {len(analysis['bills'])}")

print("\n" + "=" * 80)
