"""Vendor a Cloud catalog release, or verify the pinned release and optional source checkout.

python scripts/sync_platform_ports.py --cloud-repo ../P2HSCloud
python scripts/sync_platform_ports.py --check [--cloud-repo ../P2HSCloud]
"""
import argparse
import hashlib
import json
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
ARTIFACTS = [
    {
        'name': 'catalog',
        'source': 'packages/shared/src/platform-port-catalog.json',
        'target': ROOT / 'src/integrations/contracts/platform-port-catalog.json',
        'lock': ROOT / 'src/integrations/contracts/platform-port-catalog.release.json',
    },
    {
        'name': 'contracts',
        'source': 'packages/shared/src/platform-port-contracts.json',
        'target': ROOT / 'src/integrations/contracts/platform-port-contracts.json',
        'lock': ROOT / 'src/integrations/contracts/platform-port-contracts.release.json',
    },
]


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--cloud-repo', type=Path)
    parser.add_argument('--check', action='store_true')
    args = parser.parse_args()
    for artifact in ARTIFACTS:
        source = args.cloud_repo / artifact['source'] if args.cloud_repo else artifact['target']
        raw = source.read_bytes()
        payload = json.loads(raw)
        release = {'owner': 'P2HSCloud', 'version': payload['version'], 'sha256': hashlib.sha256(raw).hexdigest(),
                   'source': artifact['source']}
        if args.check:
            if artifact['target'].read_bytes() != raw or json.loads(artifact['lock'].read_text()) != release:
                raise SystemExit(f"Platform port release drift ({artifact['name']}): sync from the Cloud-owned catalog")
        else:
            if not args.cloud_repo:
                parser.error('--cloud-repo is required to update the release')
            artifact['target'].write_bytes(raw)
            artifact['lock'].write_text(json.dumps(release, indent=2) + '\n', encoding='utf-8', newline='\n')
        count = len(payload['ports']) if 'ports' in payload else len(payload['contracts'])
        print(f"Platform port {artifact['name']} {payload['version']}: {count} entries verified")


if __name__ == '__main__':
    main()
