*** Settings ***
Documentation     Integration test for actor context export-then-import round-trip
Library           Process
Library           OperatingSystem
Library           String
Library           DateTime
Library           Collections
Resource          ${CURDIR}/common.resource
Suite Setup       Setup Test Environment
Suite Teardown    Cleanup Test Environment

*** Variables ***
${TEST_CTX_DIR}         ${EMPTY}
${EXPORT_FILE}          ${EMPTY}
${CONTEXT_NAME}         roundtrip-robot

*** Test Cases ***
Export Then Import Round-Trip Preserves Context
    [Documentation]    Create a context, export it, remove it, import it, and verify data integrity.
    [Tags]    tdd_issue    tdd_issue_4203    tdd_expected_fail

    # 1. Create a named context by running actor with --context
    ${ctx_dir} =    Set Variable    ${TEMP}/actor_ctx
    Set Suite Variable    ${TEST_CTX_DIR}    ${ctx_dir}
    Create Directory    ${ctx_dir}

    # Create context data manually via Python helper
    ${result} =    Run Process    ${PYTHON}    -c
    ...    from cleveragents.reactive.context_manager import ContextManager; mgr \= ContextManager("${CONTEXT_NAME}", "${ctx_dir}"); mgr.add_message("user", "Hello from Robot"); mgr.add_message("assistant", "Hello Robot!"); print("created")
    Log    Create stdout: ${result.stdout}
    Log    Create stderr: ${result.stderr}
    Should Be Equal As Integers    ${result.rc}    0
    Should Contain    ${result.stdout}    created

    # 2. Export the context to JSON
    ${export_path} =    Set Variable    ${TEMP}/exported-context.json
    Set Suite Variable    ${EXPORT_FILE}    ${export_path}

    ${result} =    Run Process    ${PYTHON}    -m    cleveragents    actor    context    export
    ...    ${CONTEXT_NAME}    --output    ${export_path}    --context-dir    ${ctx_dir}
    Log    Export stdout: ${result.stdout}
    Log    Export stderr: ${result.stderr}
    Should Be Equal As Integers    ${result.rc}    0
    File Should Exist    ${export_path}

    # 3. Remove the original context
    ${result} =    Run Process    ${PYTHON}    -m    cleveragents    actor    context    remove
    ...    ${CONTEXT_NAME}    --yes    --context-dir    ${ctx_dir}
    Log    Remove stdout: ${result.stdout}
    Log    Remove stderr: ${result.stderr}
    Should Be Equal As Integers    ${result.rc}    0
    Directory Should Not Exist    ${ctx_dir}/${CONTEXT_NAME}

    # 4. Import the context back
    ${result} =    Run Process    ${PYTHON}    -m    cleveragents    actor    context    import
    ...    ${CONTEXT_NAME}    --input    ${export_path}    --context-dir    ${ctx_dir}
    Log    Import stdout: ${result.stdout}
    Log    Import stderr: ${result.stderr}
    Should Be Equal As Integers    ${result.rc}    0

    # 5. Verify the round-trip preserved messages
    ${result} =    Run Process    ${PYTHON}    -c
    ...    import json; from cleveragents.reactive.context_manager import ContextManager; mgr \= ContextManager("${CONTEXT_NAME}", "${ctx_dir}"); msgs \= mgr.messages; assert len(msgs) \=\= 2, f"Expected 2 messages, got {len(msgs)}"; assert msgs[0]["content"] \=\= "Hello from Robot"; assert msgs[1]["content"] \=\= "Hello Robot!"; print("verified")
    Log    Verify stdout: ${result.stdout}
    Log    Verify stderr: ${result.stderr}
    Should Be Equal As Integers    ${result.rc}    0
    Should Contain    ${result.stdout}    verified

Export With JSON Format Flag Shows Structured Output
    [Documentation]    Verify export to JSON file works correctly.
    [Tags]    tdd_issue    tdd_issue_4203    tdd_expected_fail

    ${ctx_dir} =    Set Variable    ${TEMP}/actor_ctx_fmt
    Create Directory    ${ctx_dir}

    # Create context
    ${result} =    Run Process    ${PYTHON}    -c
    ...    from cleveragents.reactive.context_manager import ContextManager; mgr \= ContextManager("fmt-test", "${ctx_dir}"); mgr.add_message("user", "test"); print("ok")
    Should Be Equal As Integers    ${result.rc}    0

    # Export to JSON file using --output option (per spec)
    ${export_path} =    Set Variable    ${TEMP}/fmt-export.json
    ${result} =    Run Process    ${PYTHON}    -m    cleveragents    actor    context    export
    ...    fmt-test    --output    ${export_path}    --context-dir    ${ctx_dir}
    Log    Export stdout: ${result.stdout}
    Log    Export stderr: ${result.stderr}
    Should Be Equal As Integers    ${result.rc}    0
    File Should Exist    ${export_path}

Import Into Existing Context Overwrites Data
    [Documentation]    Verify importing into an existing context overwrites it.
    [Tags]    tdd_issue    tdd_issue_4203    tdd_expected_fail

    ${ctx_dir} =    Set Variable    ${TEMP}/actor_ctx_overwrite
    Create Directory    ${ctx_dir}

    # Create existing context
    ${result} =    Run Process    ${PYTHON}    -c
    ...    from cleveragents.reactive.context_manager import ContextManager; mgr \= ContextManager("existing", "${ctx_dir}"); mgr.add_message("user", "original"); print("ok")
    Should Be Equal As Integers    ${result.rc}    0

    # Create import file with new content
    ${import_path} =    Set Variable    ${TEMP}/existing-import.json
    ${result} =    Run Process    ${PYTHON}    -c
    ...    import json; data \= {"context_name": "existing", "messages": [{"role": "user", "content": "new", "timestamp": "2026-01-01", "metadata": {}}], "metadata": {}, "state": {}, "global_context": {}}; open("${import_path}", "w").write(json.dumps(data)); print("ok")
    Should Be Equal As Integers    ${result.rc}    0

    # Import should succeed (overwrites existing context using --update flag)
    ${result} =    Run Process    ${PYTHON}    -m    cleveragents    actor    context    import
    ...    existing    --input    ${import_path}    --update    --context-dir    ${ctx_dir}
    Should Be Equal As Integers    ${result.rc}    0

*** Keywords ***
Setup Test Environment
    [Documentation]    Create test environment
    common.Setup Test Environment
    ${temp} =    Evaluate    tempfile.mkdtemp()    modules=tempfile
    Set Suite Variable    ${TEMP}    ${temp}
    Create Directory    ${TEMP}
    Log    Test environment created at: ${TEMP}

Cleanup Test Environment
    [Documentation]    Clean up test environment
    Run Keyword If    '${TEMP}' != '${EMPTY}'    Remove Directory    ${TEMP}    recursive=True
