"""
Test GCRI with CoMeT in-session memory enabled.
Exercises web search → ingest_to_memory → retrieve_from_memory flow.
"""
import sys
sys.path.insert(0, '.')

from dotenv import load_dotenv
load_dotenv()

from ato.adict import ADict
from gcri.config import scope as gcri_scope, AGENT_NAMES_IN_BRANCH
from gcri.graphs.gcri_unit import GCRI


@gcri_scope.observe('comet_test', priority=0, default=True, chain_with='no_reasoning')
def comet_test(config):
    """Enable CoMeT for all agents."""
    config.use_comet = True
    config.protocols.max_iterations = 2
    config.branches_generator_type = 'adaptive'
    config.num_branches = 2

    for agent_name in ['strategy_generator', 'decision', 'memory']:
        if hasattr(config.agents, agent_name):
            agent_cfg = getattr(config.agents, agent_name)
            if isinstance(agent_cfg, dict):
                agent_cfg = ADict(agent_cfg)
                setattr(config.agents, agent_name, agent_cfg)
            opts = agent_cfg.get('gcri_options', ADict())
            if isinstance(opts, dict) and not isinstance(opts, ADict):
                opts = ADict(opts)
            opts.use_comet = True
            agent_cfg.gcri_options = opts

    with gcri_scope.lazy():
        config.agents.branches = [
            {
                agent_name: ADict(
                    model_id='gpt-4.1-mini',
                    parameters=dict(max_tokens=25600),
                    gcri_options=ADict(
                        use_code_tools=True,
                        use_web_search=True,
                        use_comet=True,
                        max_recursion_depth=None
                    )
                ) for agent_name in AGENT_NAMES_IN_BRANCH
            } for _ in range(config.num_branches)
        ]
    return config


@gcri_scope
def main(config):
    task = """
Task: Compare the architectural differences between LangGraph and CrewAI frameworks

Search the web extensively to gather information about both frameworks.
For each framework, find:
1. Core architecture and design philosophy
2. How agents are defined and orchestrated
3. State management approach
4. Tool integration patterns
5. Key strengths and weaknesses

Write a comprehensive comparison report to 'framework_comparison.md'.
"""

    print('=' * 60)
    print('GCRI + CoMeT Integration Test')
    print('=' * 60)
    print(f'Generator: {config.branches_generator_type}')
    print(f'Branches: {config.num_branches}')
    print(f'CoMeT enabled: {getattr(config, "use_comet", False)}')
    print('=' * 60)

    gcri = GCRI(config)
    result = gcri(task)

    print('\n' + '=' * 60)
    print('Final Result:')
    print('=' * 60)
    print(f'Decision: {result.get("decision")}')

    output = result.get('output', '')
    print(f'\nOutput Preview: {output[:2000]}...')
    print('\n✅ CoMeT integration test completed.')


if __name__ == '__main__':
    main()
