import 'package:meta/meta.dart';

import 'pane.dart';

const _terminalStatuses = {'stopped', 'terminated', 'archived'};

/// One row of `sessions_detail`, matching the D8 contract in
/// `.mam/jobs/40bdce88/claude-reports/report-final.md` §3.1 field-for-field,
/// plus the additive pid/cmd_full/start_command/last_visible_status fields
/// the Detail Pane needs.
@immutable
class SessionRow {
  final String name;
  final String server;
  final String status;
  final bool tmuxAlive;
  final Pane pane;
  final String? role;
  final String resumeState;
  final String jobId;
  final String jobStatus;
  final String? attachCommand;
  final String? startCommand;
  final String? lastVisibleStatus;
  final List<String> driftClasses;

  const SessionRow({
    required this.name,
    required this.server,
    required this.status,
    required this.tmuxAlive,
    required this.pane,
    this.role,
    required this.resumeState,
    required this.jobId,
    required this.jobStatus,
    this.attachCommand,
    this.startCommand,
    this.lastVisibleStatus,
    this.driftClasses = const [],
  });

  bool get hasDrift => driftClasses.isNotEmpty;

  bool get isTerminal => _terminalStatuses.contains(status);

  factory SessionRow.fromJson(Map<String, dynamic> json) {
    return SessionRow(
      name: json['name'] as String? ?? '?',
      server: json['server'] as String? ?? 'default',
      status: json['status'] as String? ?? '?',
      tmuxAlive: json['tmux_alive'] as bool? ?? false,
      pane: Pane.fromSessionJson(json),
      role: json['role'] as String?,
      resumeState: json['resume_state'] as String? ?? '?',
      jobId: json['job_id'] as String? ?? '-',
      jobStatus: json['job_status'] as String? ?? '-',
      attachCommand: json['attach_command'] as String?,
      startCommand: json['start_command'] as String?,
      lastVisibleStatus: json['last_visible_status'] as String?,
      driftClasses: (json['drift_classes'] as List<dynamic>? ?? const [])
          .map((e) => e.toString())
          .toList(growable: false),
    );
  }
}
