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
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
"""
CardD (Card Draw Test) dataset processor.

Processes ESP card drawing test data with two schema versions:
- Old format (pre 2006-06-22): 14-15 columns, combined Markov bits
- New format (post 2006-06-22): 15-16 columns, separate Markov bits, optional image_filename
"""

from pathlib import Path
from typing import List, Dict, Any, Optional
from datetime import datetime
import pandas as pd
import re

from ..core.base_classes import BaseProcessor
from ..core.config import Config
from ..core.exceptions import ProcessorError
from ..cleaners.encoding_cleaner import EncodingCleaner
from ..cleaners.delimiter_cleaner import DelimiterCleaner
from ..cleaners.temporal_parser import TemporalParser


class CardDProcessor(BaseProcessor):
    """
    Processes CardD (Card Draw Test) data.

    Schema versions:
    - v1 (pre 2006-06-22): Markov bits combined in single 32-bit word
    - v2 (post 2006-06-22): Markov bits in separate words
    """

    # File discovery patterns
    FILE_PATTERNS = ['cardD*.dat']

    # Schema change date
    SCHEMA_CHANGE_DATE = datetime(2006, 6, 22)

    # Column definitions
    COLUMNS_OLD = [
        'user_id', 'target_bit', 'cards_done', 'cards_hit',
        'markov_stages', 'markov_output', 'markov_prob',
        'markov_bits_combined',  # Single word with both chains
        'card_number', 'is_hit', 'run_hits', 'trial_number',
        'timestamp', 'target_image', 'extra'
    ]

    COLUMNS_NEW = [
        'user_id', 'target_bit', 'cards_done', 'cards_hit',
        'markov_stages', 'markov_output', 'markov_prob',
        'markov_bits_main', 'markov_bits_aux',  # Separate words
        'card_number', 'is_hit', 'run_hits', 'trial_number',
        'timestamp', 'image_filename', 'target_image', 'extra'
    ]

    COLUMNS_UNIFIED = [
        'user_id', 'target_bit', 'cards_done', 'cards_hit',
        'markov_stages', 'markov_output', 'markov_prob',
        'markov_bits_main', 'markov_bits_aux',
        'card_number', 'is_hit', 'run_hits', 'trial_number',
        'timestamp', 'image_filename', 'target_image',
        'file_date', 'schema_version', 'source_file', 'source_row_number'
    ]

    def __init__(self, config: Config):
        """
        Initialize CardD processor.

        Args:
            config: Configuration object
        """
        super().__init__(config, 'cardd')

        # Initialize cleaners
        self.encoding_cleaner = EncodingCleaner(config, self.errata_logger)
        self.delimiter_cleaner = DelimiterCleaner(config, self.errata_logger)
        self.temporal_parser = TemporalParser(config, self.errata_logger)

        # Statistics
        self.stats = {
            'files_processed': 0,
            'files_failed': 0,
            'rows_total': 0,
            'rows_valid': 0,
            'rows_invalid': 0,
            'schema_v1_files': 0,
            'schema_v2_files': 0
        }

    def extract_file_date(self, file_path: Path) -> Optional[datetime]:
        """
        Extract date from filename (cardDYYMMDD.dat).

        Args:
            file_path: Path to file

        Returns:
            datetime object or None
        """
        match = re.search(r'cardD(\d{6})\.dat', file_path.name)
        if not match:
            return None

        date_str = match.group(1)
        return self.temporal_parser.extract_date_from_filename(file_path.name)

    def detect_schema_version(self, file_path: Path, df: pd.DataFrame) -> tuple:
        """
        Detect schema version based on file date and column count distribution.

        Checks first, middle, and last rows to detect mixed schemas.

        Args:
            file_path: Path to file
            df: DataFrame with raw data (no headers)

        Returns:
            Tuple of (primary_version, is_mixed)
            - primary_version: 'v1' or 'v2'
            - is_mixed: True if file contains both schemas
        """
        file_date = self.extract_file_date(file_path)

        # Make schema change date timezone-aware for comparison
        schema_change_aware = self.temporal_parser.timezone.localize(self.SCHEMA_CHANGE_DATE)

        # Check column count distribution across sample rows
        sample_indices = [0, len(df) // 2, len(df) - 1] if len(df) > 2 else [0]
        column_counts = []

        for idx in sample_indices:
            if idx < len(df):
                # Count non-null columns in this row
                col_count = df.iloc[idx].notna().sum()
                column_counts.append(col_count)

        unique_counts = set(column_counts)
        is_mixed = len(unique_counts) > 1

        # Determine primary version
        max_col_count = max(column_counts)

        if file_date and file_date >= schema_change_aware:
            primary_version = 'v2'
        elif max_col_count >= 15:  # v2 has >= 15 columns (separate Mbits0 and Mbits1)
            primary_version = 'v2'
        else:
            primary_version = 'v1'

        return primary_version, is_mixed

    def unpack_markov_bits_old(self, combined: int, n_stages: int) -> tuple:
        """
        Unpack combined Markov bits (old format).

        In old format, both main and aux chains stored in one 32-bit word:
        - Main chain: lower n_stages bits
        - Aux chain: next n_stages bits

        Args:
            combined: Combined 32-bit value
            n_stages: Number of Markov stages

        Returns:
            Tuple of (main_bits, aux_bits)
        """
        mask = (1 << n_stages) - 1
        main_bits = combined & mask
        aux_bits = (combined >> n_stages) & mask
        return main_bits, aux_bits

    def _process_mixed_schema_file(self, df: pd.DataFrame, file_path: Path) -> Optional[pd.DataFrame]:
        """
        Process a file with mixed schema versions (row-by-row).

        Args:
            df: Raw DataFrame with no headers
            file_path: Source file path

        Returns:
            Processed DataFrame or None
        """
        processed_rows = []
        file_date = self.extract_file_date(file_path)

        for idx, row in df.iterrows():
            try:
                # Count non-null columns to detect schema
                col_count = row.notna().sum()

                # Determine schema for this row
                if col_count >= 15:
                    # v2 schema (new format with separate Markov bits)
                    schema = 'v2'
                    columns = self.COLUMNS_NEW[:col_count]
                elif col_count >= 14:
                    # v1 schema (old format with combined Markov bits)
                    schema = 'v1'
                    columns = self.COLUMNS_OLD[:col_count]
                else:
                    # Insufficient columns, skip row
                    continue

                # Create dict for this row
                row_dict = {}
                for i, col_name in enumerate(columns):
                    if i < len(row):
                        row_dict[col_name] = row.iloc[i]

                # Handle old format: unpack combined Markov bits
                if schema == 'v1' and 'markov_bits_combined' in row_dict:
                    try:
                        n_stages = int(row_dict.get('markov_stages', 0))
                        combined = int(row_dict['markov_bits_combined'])
                        main_bits, aux_bits = self.unpack_markov_bits_old(combined, n_stages)
                        row_dict['markov_bits_main'] = main_bits
                        row_dict['markov_bits_aux'] = aux_bits
                        del row_dict['markov_bits_combined']
                    except (ValueError, TypeError):
                        # Skip row if unpacking fails
                        continue

                # Add metadata
                row_dict['file_date'] = file_date
                row_dict['schema_version'] = schema

                # Add audit columns (source file and row numbers)
                row_dict['source_file'] = file_path.name
                row_dict['source_row_number'] = idx + 1

                # Remove 'extra' column if present
                if 'extra' in row_dict:
                    del row_dict['extra']

                processed_rows.append(row_dict)

            except Exception as e:
                import traceback
                self.errata_logger.log_error(
                    'row_processing_failed',
                    f'Row {idx}: {type(e).__name__}: {e}',
                    file_path=str(file_path),
                    scope='row',
                    line_number=idx,
                    context={'traceback': traceback.format_exc()},
                )
                continue

        if not processed_rows:
            return None

        # Create DataFrame from processed rows
        result_df = pd.DataFrame(processed_rows)

        # Validate and clean
        result_df = self.validate_dataframe(result_df, file_path)

        # Ensure all unified columns exist AFTER validation
        for col in self.COLUMNS_UNIFIED:
            if col not in result_df.columns:
                result_df[col] = None

        # Reorder to unified schema
        result_df = result_df[self.COLUMNS_UNIFIED]

        return result_df

    def process_file(self, file_path: Path, pre_cleaned_text: Optional[str] = None) -> Optional[pd.DataFrame]:
        """
        Process a single CardD file.

        Args:
            file_path: Path to file
            pre_cleaned_text: Pre-cleaned text from parallel batch cleaning.
                If None, cleans the file inline (backward compat).

        Returns:
            DataFrame or None if processing fails
        """
        try:
            # Use pre-cleaned text if available, otherwise clean inline
            if pre_cleaned_text is not None:
                text = pre_cleaned_text
            else:
                text = self.encoding_cleaner.clean(file_path)
                text = self.delimiter_cleaner.clean(text, file_path=str(file_path))

            # Pre-validate lines so bad rows are logged before being removed
            text = self.pre_validate_csv_lines(text, file_path=str(file_path))

            from io import BytesIO
            df = pd.read_csv(BytesIO(text.encode('utf-8')), header=None, on_bad_lines='skip', engine='pyarrow')

            if df.empty:
                self.errata_logger.log_error(
                    'empty_file',
                    'File is empty or has no valid rows - entire file omitted',
                    file_path=str(file_path),
                    scope='file'
                )
                return None

            # Detect schema version and check for mixed schemas
            schema_version, is_mixed = self.detect_schema_version(file_path, df)

            if is_mixed:
                self.errata_logger.log_error(
                    'mixed_schema_detected',
                    f'File contains mixed schema versions (v1 and v2)',
                    file_path=str(file_path),
                    scope='row'
                )
                # Process row-by-row for mixed schema files
                return self._process_mixed_schema_file(df, file_path)

            # Single schema processing (original logic)
            column_count = len(df.columns)

            # Assign column names
            if schema_version == 'v1':
                if column_count >= 14:
                    df.columns = self.COLUMNS_OLD[:column_count]
                    self.stats['schema_v1_files'] += 1
                else:
                    self.errata_logger.log_error(
                        'insufficient_columns',
                        f'Too few columns: {column_count} - entire file omitted',
                        file_path=str(file_path),
                        scope='file'
                    )
                    return None
            else:  # v2
                if column_count >= 15:
                    df.columns = self.COLUMNS_NEW[:column_count]
                    self.stats['schema_v2_files'] += 1
                else:
                    self.errata_logger.log_error(
                        'insufficient_columns',
                        f'Too few columns: {column_count} - entire file omitted',
                        file_path=str(file_path),
                        scope='file'
                    )
                    return None

            # Unpack Markov bits for old format
            if schema_version == 'v1' and 'markov_bits_combined' in df.columns:
                df[['markov_bits_main', 'markov_bits_aux']] = df.apply(
                    lambda row: pd.Series(
                        self.unpack_markov_bits_old(
                            row['markov_bits_combined'],
                            row['markov_stages']
                        )
                    ),
                    axis=1
                )
                df = df.drop(columns=['markov_bits_combined'])

            # Add metadata
            file_date = self.extract_file_date(file_path)
            df['file_date'] = file_date
            df['schema_version'] = schema_version

            # Add audit columns (source file and row numbers)
            df['source_file'] = file_path.name
            df['source_row_number'] = range(1, len(df) + 1)

            # Remove 'extra' column if present (not needed in unified schema)
            if 'extra' in df.columns:
                df = df.drop(columns=['extra'])

            # Validate and clean
            df = self.validate_dataframe(df, file_path)

            # Ensure all unified columns exist AFTER validation
            for col in self.COLUMNS_UNIFIED:
                if col not in df.columns:
                    df[col] = None

            # Reorder to unified schema
            df = df[self.COLUMNS_UNIFIED]

            self.stats['files_processed'] += 1
            self.stats['rows_valid'] += len(df)
            return df

        except Exception as e:
            import traceback
            self.errata_logger.log_error(
                'file_processing_failed',
                f'{type(e).__name__}: {e} - entire file omitted',
                file_path=str(file_path),
                scope='file',
                context={'traceback': traceback.format_exc()},
            )
            return None

    def validate_dataframe(self, df: pd.DataFrame, file_path: Path) -> pd.DataFrame:
        """
        Validate and clean DataFrame.

        Args:
            df: Input DataFrame
            file_path: Source file path

        Returns:
            Cleaned DataFrame
        """
        initial_count = len(df)
        valid_mask = pd.Series([True] * len(df), index=df.index)


        # Validate user_id length
        long_users = df['user_id'].str.len() > 64
        if long_users.any():
            valid_mask &= ~long_users
            self.errata_logger.log_error(
                'user_id_too_long',
                f'{long_users.sum()} rows with user_id > 64 chars',
                file_path=str(file_path),
                scope='row'
            )

        # Validate card_number range (0-4)
        if 'card_number' in df.columns:
            df['card_number'] = self.to_numeric_logged(df['card_number'], 'card_number', str(file_path))
            invalid_card = (df['card_number'] < 0) | (df['card_number'] > 4)
            if invalid_card.any():
                valid_mask &= ~invalid_card
                self.errata_logger.log_error(
                    'card_number_out_of_range',
                    f'{invalid_card.sum()} rows with card_number not in 0-4',
                    file_path=str(file_path),
                    scope='row'
                )

        # Validate trial_number (must be >= 1, no upper limit since trperrun is configurable)
        if 'trial_number' in df.columns:
            df['trial_number'] = self.to_numeric_logged(df['trial_number'], 'trial_number', str(file_path))
            invalid_trial = (df['trial_number'] < 1)
            if invalid_trial.any():
                valid_mask &= ~invalid_trial
                self.errata_logger.log_error(
                    'trial_number_invalid',
                    f'{invalid_trial.sum()} rows with trial_number < 1',
                    file_path=str(file_path),
                    scope='row'
                )

        # Validate cards_done/cards_hit
        for col in ['cards_done', 'cards_hit']:
            if col in df.columns:
                df[col] = self.to_numeric_logged(df[col], col, str(file_path))
                invalid = (df[col] < 0) | (df[col] > 5)
                if invalid.any():
                    valid_mask &= ~invalid

        # Parse timestamps
        if 'timestamp' in df.columns:
            df['timestamp'] = self.temporal_parser.parse_dates_vectorized(
                df['timestamp'], file_path=str(file_path)
            )

        # Convert numeric columns
        numeric_cols = [
            'target_bit', 'cards_done', 'cards_hit', 'markov_stages',
            'markov_output', 'markov_prob', 'markov_bits_main', 'markov_bits_aux',
            'card_number', 'is_hit', 'run_hits', 'trial_number'
        ]

        for col in numeric_cols:
            if col in df.columns:
                df[col] = self.to_numeric_logged(df[col], col, str(file_path))

        # Filter to valid rows
        df_valid = df[valid_mask].copy()

        invalid_count = initial_count - len(df_valid)
        if invalid_count > 0:
            self.errata_logger.log_file_summary(
                str(file_path),
                'partial',
                initial_count,
                len(df_valid),
                invalid_count
            )

        return df_valid

    def get_stats(self) -> Dict[str, Any]:
        """Get processing statistics."""
        return self.stats.copy()