"""Display helpers for CLI output."""

from __future__ import annotations

import sys
from typing import Any

from .timeutil import parse_timestamp


def display_warnings(warnings: list[str]) -> None:
    for warning in warnings:
        print(warning, file=sys.stderr)


def display_time_info(time_info: dict[str, Any] | None, is_combined: bool = False) -> None:
    if not time_info:
        return

    first_timestamp = parse_timestamp(str(time_info["first_timestamp"]))
    last_timestamp = parse_timestamp(str(time_info["last_timestamp"]))
    time_span = (last_timestamp - first_timestamp).total_seconds() / 60.0

    if is_combined:
        file_count = time_info.get("file_count", 1)
        print(f"\nCOMBINED TIME REPORT ({file_count} recordings):", file=sys.stderr)
        print(
            f"Total elapsed editing time: {time_info['minutes_elapsed']} minutes",
            file=sys.stderr,
        )
        print(f"Overall time span: {time_span:.2f} minutes", file=sys.stderr)
    else:
        print(
            f"Elapsed editing time: {time_info['minutes_elapsed']} minutes",
            file=sys.stderr,
        )
        print(
            f"Time span (first to last edit): {time_span:.2f} minutes",
            file=sys.stderr,
        )

    if time_info.get("exceeds_limit"):
        print("\nTime limit exceeded!", file=sys.stderr)
        print(f"  Limit: {time_info['time_limit_minutes']} minutes", file=sys.stderr)
        if not is_combined:
            print(f"  First edit: {time_info['first_timestamp']}", file=sys.stderr)
            print(f"  Last edit: {time_info['last_timestamp']}", file=sys.stderr)


def display_editors(editors: set[str]) -> None:
    if editors:
        print(f"Editors: {', '.join(sorted(editors))}", file=sys.stderr)


def _display_code_block(
    content: str,
    indent: str = "    ",
    *,
    max_lines: int | None = None,
) -> None:
    lines = content.split("\n")
    truncated = max_lines is not None and len(lines) > max_lines
    visible_lines = lines[:max_lines] if truncated and max_lines is not None else lines

    print(f"{indent}```", file=sys.stderr)
    for line in visible_lines:
        print(f"{indent}{line}", file=sys.stderr)
    if truncated:
        print(f"{indent}...", file=sys.stderr)
    print(f"{indent}```", file=sys.stderr)


def display_suspicious_event(
    event: dict[str, Any],
    show_details: bool,
    verbose: bool,
) -> None:
    reason = event.get("reason", "unknown")
    max_lines = None if verbose else 12

    if "event_indices" in event:
        indices = event["event_indices"]
        print(
            f"  Events #{indices[0]}-#{indices[-1]} ({reason}): "
            f"{event['line_count']} lines, {event['char_count']} chars",
            file=sys.stderr,
        )
        if (show_details or verbose) and event.get("detailed_events"):
            combined_content = "".join(
                detail["newFragment"] for detail in event["detailed_events"]
            ).rstrip("\n")
            print("    Combined output:", file=sys.stderr)
            _display_code_block(
                combined_content,
                indent="        ",
                max_lines=max_lines,
            )
        return

    print(
        f"  Event #{event['event_index']} ({reason}): "
        f"{event['line_count']} lines, {event['char_count']} chars",
        file=sys.stderr,
    )
    if reason == "conflicting snapshot":
        snippet = event.get("diff", "").strip("\n")
    else:
        snippet = event.get("newFragment", "").strip("\n")
    if snippet:
        _display_code_block(snippet, max_lines=max_lines)


def display_suspicious_events(
    suspicious_events: list[dict[str, Any]],
    show_details: bool,
    verbose: bool,
) -> None:
    if suspicious_events:
        print("\nSuspicious events detected:", file=sys.stderr)
        for event in suspicious_events:
            display_suspicious_event(event, show_details, verbose)
    else:
        print("Success! No suspicious events detected.", file=sys.stderr)


def display_template_diff(diff_text: str) -> None:
    if not diff_text.strip():
        return

    print("\nTemplate mismatch diff:", file=sys.stderr)
    print(diff_text, file=sys.stderr)


def display_submitted_file_comparison(comparison: dict[str, Any] | None) -> None:
    if not comparison:
        return

    print("Submitted file comparison:", file=sys.stderr)
    print(f"  Submitted file: {comparison['submitted_file']}", file=sys.stderr)

    if "error" in comparison:
        print(f"  Error: {comparison['error']}", file=sys.stderr)
        return

    if comparison.get("matches"):
        print("  Reconstructed code matches submitted file exactly", file=sys.stderr)
        return

    if comparison.get("whitespace_only"):
        print(
            "  Reconstructed code differs only in whitespace from submitted file",
            file=sys.stderr,
        )
    else:
        print("  Reconstructed code differs from submitted file", file=sys.stderr)

    if comparison.get("diff"):
        print("\n  Diff (reconstructed -> submitted):", file=sys.stderr)
        for line in comparison["diff"].splitlines():
            print(f"    {line}", file=sys.stderr)


def print_separator() -> None:
    print("=" * 80, file=sys.stderr)


def print_batch_header(current: int, total: int, filename: str) -> None:
    print_separator()
    print(f"[{current}/{total}] Processing: {filename}", file=sys.stderr)
    print_separator()


def print_batch_summary(
    total_files: int,
    verified_count: int,
    combined_time_info: dict[str, Any] | None,
    submitted_all_passed: bool | None = None,
) -> None:
    print_separator()
    print(f"BATCH SUMMARY: Processed {total_files} files", file=sys.stderr)
    print_separator()
    print(f"Verified: {verified_count}/{total_files}", file=sys.stderr)
    if submitted_all_passed is not None:
        print(f"Submitted comparisons passed: {submitted_all_passed}", file=sys.stderr)
    if combined_time_info is not None:
        display_time_info(combined_time_info, is_combined=True)
