using ExcelDataReader;
using System.Text;

// Register encoding provider for older Excel formats
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

string filePath = @"Y:\PCC\Quickbooks\Online\Customers.xls";

try
{
    Console.WriteLine($"Inspecting file: {filePath}");
    Console.WriteLine($"File size: {new FileInfo(filePath).Length / 1024} KB");
    Console.WriteLine();

    using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
    {
        // Auto-detect format (.xls or .xlsx)
        using (var reader = ExcelReaderFactory.CreateReader(stream))
        {
            // Read the first worksheet
            reader.Read(); // Move to first row (headers)

            // Get column count
            int columnCount = reader.FieldCount;
            Console.WriteLine($"Total columns: {columnCount}");

            // Count total rows
            int rowCount = 1; // We're already on row 1
            while (reader.Read())
            {
                rowCount++;
            }
            Console.WriteLine($"Total rows: {rowCount}");
            Console.WriteLine();

            // Reset to beginning to read headers and data
            reader.Reset();
            reader.Read(); // Move to first row (headers)

            // Read and display headers
            Console.WriteLine("=== HEADERS (Row 1) ===");
            var headers = new string[columnCount];
            for (int col = 0; col < columnCount; col++)
            {
                headers[col] = reader.GetValue(col)?.ToString() ?? $"Column{col + 1}";
                Console.WriteLine($"Column {col + 1}: {headers[col]}");
            }
            Console.WriteLine();

            // Read and display sample data (row 2)
            Console.WriteLine("=== SAMPLE DATA (Row 2) ===");
            if (reader.Read()) // Move to second row
            {
                for (int col = 0; col < columnCount; col++)
                {
                    var value = reader.GetValue(col)?.ToString() ?? "(empty)";
                    Console.WriteLine($"{headers[col]}: {value}");
                }
            }
            else
            {
                Console.WriteLine("No data rows found (only headers or empty file)");
            }
        }
    }
}
catch (Exception ex)
{
    Console.WriteLine($"ERROR: {ex.GetType().Name}");
    Console.WriteLine($"Message: {ex.Message}");
    Console.WriteLine($"Stack: {ex.StackTrace}");
}
