from datetime import datetime

from abx_dl.cli import _build_archive_results_table, _compact_output, _format_archive_result_line, _format_elapsed
from abx_dl.models import ArchiveResult


def test_compact_output_collapses_whitespace_and_truncates() -> None:
    text = "line one\n\nline two\tline three"
    assert _compact_output(text, limit=20) == "line one line two..."


def test_format_archive_result_line_includes_requested_fields() -> None:
    result = ArchiveResult(
        snapshot_id='snap',
        plugin='chrome',
        hook_name='on_Snapshot__10_chrome_tab.bg',
        status='failed',
        output_str='',
        error='No Chrome session found',
    )

    line = _format_archive_result_line(result)

    assert 'ArchiveResult' in line
    assert 'on_Snapshot__10_chrome_tab.bg' in line
    assert 'failed' in line
    assert 'No Chrome session found' in line


def test_format_elapsed_uses_running_or_completed_timestamps() -> None:
    now = datetime(2026, 3, 11, 12, 0, 15)

    running = _format_elapsed('2026-03-11T12:00:00', None, 60, now=now)
    completed = _format_elapsed('2026-03-11T12:00:00', '2026-03-11T12:00:05', 60, now=now)

    assert running == '15.0s/60s'
    assert completed == '5.0s/60s'


def test_build_archive_results_table_includes_elapsed_column() -> None:
    result = ArchiveResult(
        snapshot_id='snap',
        plugin='chrome',
        hook_name='on_Snapshot__10_chrome_tab.bg',
        status='started',
        start_ts='2026-03-11T12:00:00',
    )

    table = _build_archive_results_table([result], timeout_seconds=60, now=datetime(2026, 3, 11, 12, 0, 5))

    assert [column.header for column in table.columns] == ['Type', 'Hook Name', 'Status', 'Elapsed', 'Output']
    elapsed_cells = table.columns[3]._cells
    assert elapsed_cells == ['5.0s/60s']
