#!/usr/bin/env python3
"""Extract a GDR packet-session config command list into a host-request JSONL."""
from __future__ import annotations
import argparse, json
from pathlib import Path
from typing import Any, Dict


def get_by_dotted(obj: Dict[str, Any], dotted: str) -> Any:
    cur: Any = obj
    for part in dotted.split('.'):
        if not isinstance(cur, dict) or part not in cur:
            return None
        cur = cur[part]
    return cur


def main() -> int:
    ap = argparse.ArgumentParser(description='Convert trace.gdr_packet_session_model.commands to request JSONL')
    ap.add_argument('--config', required=True)
    ap.add_argument('--out', required=True)
    ap.add_argument('--model-path', default='trace.gdr_packet_session_model')
    args = ap.parse_args()
    cfg = json.loads(Path(args.config).read_text(encoding='utf-8'))
    model = get_by_dotted(cfg, args.model_path)
    if not isinstance(model, dict) or not isinstance(model.get('commands'), list):
        raise SystemExit(f'no commands at {args.model_path}')
    rows = []
    for i, cmd in enumerate(model['commands']):
        row = {
            'index': i,
            'tag': cmd.get('tag') or cmd.get('title') or f'cmd_{i:03d}',
            'cdb_hex': cmd.get('cdb_hex') or cmd.get('cdb') or '',
        }
        if str(cmd.get('direction','')).lower() == 'out' and (cmd.get('data_out_hex') or cmd.get('data_out')):
            row['data_out_hex'] = cmd.get('data_out_hex') or cmd.get('data_out')
        rows.append(row)
    out = Path(args.out)
    out.parent.mkdir(parents=True, exist_ok=True)
    with out.open('w', encoding='utf-8') as f:
        for r in rows:
            f.write(json.dumps(r, separators=(',',':')) + '\n')
    print(f'[OK] wrote {len(rows)} requests: {out}')
    return 0

if __name__ == '__main__':
    raise SystemExit(main())
