#!/usr/bin/env python3
"""
Test the monop parser by replaying historical log and validating checkpoints.
"""

import sys
import os
sys.path.insert(0, os.path.dirname(__file__))

from monop_parser import MonopParser, SQUARE_BY_NAME


def test_log_replay(filepath="test_data/monop.log"):
    parser = MonopParser()
    total_lines = 0
    bot_lines = 0

    with open(filepath, 'r') as f:
        for line in f:
            line = line.rstrip('\n')
            total_lines += 1
            parts = line.split('\t')
            if len(parts) >= 3 and parts[1].strip() == "monop":
                bot_lines += 1
            parser.parse_line(line)

    print(f"=== Log Replay Results ===")
    print(f"Total lines: {total_lines}")
    print(f"Bot lines: {bot_lines}")
    print(f"Games found: {len(parser.games)}")
    print(f"Checkpoints validated: {parser.checkpoints_validated}")
    print(f"Checkpoints failed: {parser.checkpoints_failed}")
    print(f"Mismatch rate: {parser.checkpoints_failed}/{parser.checkpoints_validated + parser.checkpoints_failed}")

    if parser.checkpoint_errors:
        print(f"\n=== First 50 Errors ===")
        for err in parser.checkpoint_errors[:50]:
            print(f"  {err}")

    # 2 mismatches are expected: lines 11674 and 11682 have 7 IRC disconnects
    # between checkpoints, causing lost bot output that can't be reconstructed
    max_acceptable = 2
    status = "PASS" if parser.checkpoints_failed <= max_acceptable else "FAIL"
    print(f"\n{status}: "
          f"{parser.checkpoints_validated} checkpoints validated, "
          f"{parser.checkpoints_failed} mismatches "
          f"(max acceptable: {max_acceptable}, caused by IRC disconnects)")

    return parser.checkpoints_failed <= max_acceptable


if __name__ == "__main__":
    os.chdir(os.path.dirname(__file__) or ".")
    success = test_log_replay()
    sys.exit(0 if success else 1)
