import 'package:oto/oto/application.dart';
import 'package:oto/oto/core/execution_context.dart';
import 'package:oto/oto/core/tag_system.dart';
import 'package:test/test.dart';

void main() {
  setUp(() {
    Application.instance.context = ExecutionContext();
  });

  test('context backs application compatibility accessors', () {
    Application.instance.property['workspace'] = '/tmp/oto';
    Application.instance.commandStates['step'] = CommandState.progress;

    expect(Application.instance.context.property['workspace'], '/tmp/oto');
    expect(Application.instance.context.commandStates['step'],
        CommandState.progress);

    Application.instance.context.property['key'] = 'value';
    expect(Application.instance.property['key'], 'value');
  });

  test('tag system reads and writes through execution context', () async {
    await TagSystem.setPropertyValue('<@property.appVersion>', '1.2.3',
        showPrint: false);

    expect(Application.instance.context.property['appVersion'], '1.2.3');
    expect(TagSystem.replaceTagValue('<!property.appVersion>'), '1.2.3');

    Application.instance.context.commandStates['build'] = CommandState.complete;
    expect(TagSystem.replaceTagValue('<!state.build>'), 'complete');
  });

  test('execution context records and resets step events', () {
    final context = Application.instance.context;
    expect(context.stepEvents, isEmpty);

    final id1 = context.allocateStepEventId();
    final event1 = StepEvent(
      stepId: id1,
      workflowIndex: 0,
      stepType: 'exe',
      event: 'started',
      timestamp: '2026-05-22T04:59:40Z',
      commandId: 'hello',
      commandType: 'Print',
    );
    context.addStepEvent(event1);

    expect(context.stepEvents, hasLength(1));
    final json = context.stepEvents.first.toJson();
    expect(json['schemaVersion'], 1);
    expect(json['type'], 'stepEvent');
    expect(json['event'], 'started');
    expect(json['stepId'], 0);
    expect(json['workflowIndex'], 0);
    expect(json['stepType'], 'exe');
    expect(json['commandId'], 'hello');
    expect(json['commandType'], 'Print');
    expect(json['timestamp'], '2026-05-22T04:59:40Z');
    expect(json['error'], isNull);

    final id2 = context.allocateStepEventId();
    expect(id2, 1);

    context.resetStepEvents();
    expect(context.stepEvents, isEmpty);
    expect(context.allocateStepEventId(), 0);
  });
}
