import json, subprocess, os, datetime
TS = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
backup_dir = '/home/admin/docker-network-backups'
os.makedirs(backup_dir, exist_ok=True)
names = subprocess.check_output(['docker','network','ls','--format','{{.Name}}'], text=True).splitlines()
all_data = []
for name in names:
    raw = subprocess.check_output(['docker','network','inspect',name], text=True)
    obj = json.loads(raw)[0]
    containers = []
    for _, c in (obj.get('Containers') or {}).items():
        containers.append({
            'name': c.get('Name'),
            'ipv4': c.get('IPv4Address'),
            'ipv6': c.get('IPv6Address')
        })
    containers.sort(key=lambda x: x['name'] or '')
    all_data.append({
        'name': obj.get('Name'),
        'driver': obj.get('Driver'),
        'scope': obj.get('Scope'),
        'internal': obj.get('Internal'),
        'subnets': [cfg.get('Subnet') for cfg in (obj.get('IPAM',{}).get('Config') or []) if cfg.get('Subnet')],
        'gateways': [cfg.get('Gateway') for cfg in (obj.get('IPAM',{}).get('Config') or []) if cfg.get('Gateway')],
        'containers': containers,
    })
json_path = f'{backup_dir}/networks_{TS}.json'
md_path = f'{backup_dir}/networks_{TS}.md'
with open(json_path, 'w', encoding='utf-8') as f:
    json.dump(all_data, f, ensure_ascii=False, indent=2)
with open(md_path, 'w', encoding='utf-8') as f:
    f.write('# Docker network backup\n\n')
    for n in all_data:
        f.write(f"## {n['name']}\n")
        f.write(f"- driver: {n['driver']}\n")
        f.write(f"- scope: {n['scope']}\n")
        f.write(f"- internal: {n['internal']}\n")
        f.write(f"- subnets: {', '.join(n['subnets']) if n['subnets'] else '(none)'}\n")
        f.write(f"- gateways: {', '.join(n['gateways']) if n['gateways'] else '(none)'}\n")
        f.write(f"- containers: {len(n['containers'])}\n")
        for c in n['containers']:
            f.write(f"  - {c['name']} {c['ipv4'] or ''}\n")
        f.write('\n')
print('BACKUP_JSON', json_path)
print('BACKUP_MD', md_path)
print('\nNETWORK_SUMMARY')
for n in all_data:
    print(f"{n['name']}: driver={n['driver']} containers={len(n['containers'])}")
keep = {'bridge','host','none','new-api_default','nanobot-nthk90_default','nanobot-sqyyqssqyyqs_default','infra_shared'}
if subprocess.run(['docker','network','inspect','infra_shared'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode != 0:
    subprocess.check_call(['docker','network','create','infra_shared'])
    print('\nCREATED infra_shared')
else:
    print('\ninfra_shared already exists')
remove = []
for n in all_data:
    if n['name'] in keep:
        continue
    if n['driver'] in ('host','null'):
        continue
    if n['containers']:
        continue
    remove.append(n['name'])
print('\nREMOVE_EMPTY_CUSTOM', remove)
for name in remove:
    subprocess.check_call(['docker','network','rm',name])
print('\nFINAL_NETWORKS')
print(subprocess.check_output(['docker','network','ls'], text=True))
