#!/usr/bin/env python3
"""
Builds the Postman collection + local environment from docs/openapi.json.

    php artisan scramble:export && python3 docs/postman/build_collection.py

Every operation in the OpenAPI document becomes a request. Bodies come from the
hand-written test data in BODIES (realistic Paschim Today values); anything not
listed there falls back to an example generated from the schema, so new endpoints
still appear. Test scripts save uids/tokens into variables so requests chain.
"""
import hashlib
import json
import os
import re
import sys
import uuid

ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
HERE = os.path.join(ROOT, 'docs', 'postman')
OPENAPI = os.path.join(ROOT, 'docs', 'openapi.json')
COLLECTION_ONLY = '--collection-only' in sys.argv
build_args = [arg for arg in sys.argv[1:] if arg != '--collection-only']
WORKFLOWS_JSON = build_args[0] if build_args else None  # optional dump of seeders/data/workflows.php

spec = json.load(open(OPENAPI, encoding='utf-8'))
schemas = spec['components']['schemas']


def fixture(name):
    path = os.path.join(HERE, 'fixtures', name)
    data = open(path, 'rb').read()
    return {'src': 'docs/postman/fixtures/' + name, 'size': len(data), 'sha256': hashlib.sha256(data).hexdigest()}


PHOTO = fixture('sample-photo.jpg')
PRESS = fixture('press-card.jpg')
PDF = fixture('citizenship.pdf')

# ---------------------------------------------------------------------------
# Test data
# ---------------------------------------------------------------------------
STORY = {
    'content_type': 'news',
    'language': 'ne',
    'slug': '{{story_slug}}',
    'headline': {'ne': 'धनगढीमा भारी वर्षा, सेती नदीको बहाव बढ्यो', 'en': 'Heavy rain in Dhangadhi raises the Seti river'},
    'short_headline': {'ne': 'धनगढीमा भारी वर्षा', 'en': 'Heavy rain in Dhangadhi'},
    'subheadline': {'ne': 'तटीय बस्तीलाई सतर्क रहन प्रशासनको आग्रह', 'en': 'Administration asks riverside settlements to stay alert'},
    'summary': {'ne': 'लगातारको वर्षाले कैलालीका नदीहरूमा पानीको सतह बढेको छ।', 'en': 'Continuous rain has raised river levels across Kailali.'},
    'key_points': ['सेती नदी खतराको तहनजिक', 'जिल्ला प्रशासन कार्यालयले उद्धार टोली तयार राखेको', 'विद्यालय दुई दिन बन्द'],
    'body_html': '<p>धनगढी — लगातारको वर्षाका कारण कैलालीका प्रमुख नदीहरूमा पानीको सतह बढेको छ।</p><p>जिल्ला प्रशासन कार्यालयका अनुसार उद्धार टोली तयारी अवस्थामा छन्।</p>',
    'body_blocks': [
        {'type': 'paragraph', 'data': {'text': 'धनगढी — लगातारको वर्षाका कारण कैलालीका प्रमुख नदीहरूमा पानीको सतह बढेको छ।'}},
        {'type': 'quote', 'data': {'text': 'उद्धार टोली २४ सै घण्टा तयारी अवस्थामा छन्।', 'cite': 'प्रमुख जिल्ला अधिकारी'}},
    ],
    'categories': ['{{category_uid}}'],
    'primary_category': '{{category_uid}}',
    'locations': [{'province': 'sudurpaschim', 'district': 'kailali', 'local_level': 'dhangadhi', 'ward': 5}],
    'flags': {'breaking': False, 'featured': True, 'exclusive': False, 'sponsored': False},
    'seo': {'title': {'ne': 'धनगढीमा भारी वर्षा', 'en': 'Heavy rain in Dhangadhi'}, 'description': {'ne': 'कैलालीमा नदीको बहाव बढ्यो', 'en': 'River levels rise in Kailali'}},
    'sources': [
        {'type': 'person', 'name': 'जिल्ला प्रशासन कार्यालय, कैलाली', 'notes': 'फोन वार्ता, बिहान ९ बजे', 'confidential': False},
        {'type': 'link', 'name': 'जल तथा मौसम विज्ञान विभाग', 'url': 'https://www.dhm.gov.np', 'confidential': False},
    ],
    'priority': 'P2',
    'reason': 'First draft from the Kailali desk',
}
STORY_UPDATE = {k: STORY[k] for k in ('headline', 'categories', 'locations')}
STORY_UPDATE['headline'] = {'ne': 'धनगढीमा भारी वर्षा, सेती नदी खतराको तहमा', 'en': 'Heavy rain in Dhangadhi pushes the Seti river to danger level'}
STORY_UPDATE['body_html'] = STORY['body_html'] + '<p>पछिल्लो अपडेट: सेती नदी खतराको तहमा पुगेको छ।</p>'
STORY_UPDATE['reason'] = 'Updated river level'

TAXON_SEO = {'title': {'ne': 'सुदूरपश्चिम समाचार', 'en': 'Sudurpaschim news'}, 'description': {'ne': 'सुदूरपश्चिमका ताजा समाचार', 'en': 'Latest news from Sudurpaschim'}, 'keywords': {'ne': 'सुदूरपश्चिम, कैलाली', 'en': 'Sudurpaschim, Kailali'}}

FUTURE = '{{tomorrow_iso}}'
LATER = '{{in_two_days_iso}}'

BODIES = {
    # --- Analytics / scorecards -------------------------------------------------
    'POST /v1/events': {'visitor_id': '{{device_id}}', 'surface': 'web', 'district': 'kailali', 'events': [
        {'type': 'view', 'story': '{{story_uid}}'},
        {'type': 'read_progress', 'story': '{{story_uid}}', 'value': 90},
        {'type': 'engaged_seconds', 'story': '{{story_uid}}', 'value': 45},
        {'type': 'share', 'story': '{{story_uid}}', 'network': 'whatsapp'},
    ]},
    'POST /v1/cms/analytics/exports': {'report': 'leaderboard', 'format': 'csv', 'params': {'period': '7d', 'dimension': 'story', 'metric': 'views'}},
    'PUT /v1/cms/analytics/alert-rules/{key}': {'params': {'min_views': 2000}, 'reason': 'Tune the viral-story threshold'},
    'PUT /v1/cms/scorecards/weights': {'weights': {'accuracy': 35, 'relevance': 20, 'acceptance': 15, 'edit_intensity': 10, 'timeliness': 10, 'impact': 10}, 'reason': 'Default credibility weights'},
    'POST /v1/cms/stories/{story}/accuracy-flags': {'kind': 'factual_error', 'evidence': 'Ward office confirmed the figure was 12, not 120.'},
    'POST /v1/cms/accuracy-flags/{flag}/revoke': {'reason': 'The source document confirms the original figure.'},
    'POST /v1/cms/scorecards/appeals': {'flag': '{{accuracy_flag_uid}}', 'reason': 'The original DAO press release confirms the figure.'},
    'POST /v1/cms/scorecards/appeals/{appeal}/decide': {'decision': 'upheld', 'note': 'The DAO source document checks out.'},
    # --- Auth ------------------------------------------------------------------
    'POST /v1/auth/login': {'login': '{{login}}', 'password': '{{password}}', 'device_id': '{{device_id}}', 'device_name': 'Postman'},
    'POST /v1/auth/2fa/challenge': {'challenge_token': '{{challenge_token}}', 'code': '{{two_factor_code}}', 'device_id': '{{device_id}}', 'device_name': 'Postman'},
    'POST /v1/auth/2fa/challenge/resend': {'challenge_token': '{{challenge_token}}'},
    'POST /v1/auth/refresh': {'refresh_token': '{{refresh_token}}', 'device_id': '{{device_id}}', 'device_name': 'Postman'},
    'POST /v1/auth/logout': {'all': False},
    'POST /v1/auth/register': {'name': 'सीता भट्ट', 'phone': '{{reader_phone}}', 'password': 'Dhangadhi-2083!', 'password_confirmation': 'Dhangadhi-2083!'},
    'POST /v1/auth/otp/send': {'target': '{{reader_phone}}', 'purpose': 'login'},
    'POST /v1/auth/otp/verify': {'target': '{{reader_phone}}', 'code': '{{otp_code}}', 'device_id': '{{device_id}}', 'device_name': 'Postman'},
    'POST /v1/auth/login/otp': {'phone': '{{reader_phone}}', 'code': '{{otp_code}}', 'device_id': '{{device_id}}', 'device_name': 'Postman'},
    'POST /v1/auth/password/forgot': {'email': 'sita.bhatt@example.com'},
    'POST /v1/auth/password/reset': {'email': 'sita.bhatt@example.com', 'token': '{{password_reset_token}}', 'password': 'Kailali-Naya-2083!', 'password_confirmation': 'Kailali-Naya-2083!'},
    'POST /v1/auth/invitations/accept': {'token': '{{invitation_token}}', 'name': 'हरि जोशी', 'username': 'hari.joshi{{$randomInt}}', 'password': 'Newsroom-2083!', 'password_confirmation': 'Newsroom-2083!', 'device_id': '{{device_id}}', 'device_name': 'Postman'},
    'POST /v1/auth/register/reporter': [
        ('name', 'text', 'राम प्रसाद जोशी'),
        ('email', 'text', 'ram.joshi.{{$timestamp}}@example.com'),
        ('phone', 'text', '9858012345'),
        ('password', 'text', 'Reporter-2083!'),
        ('password_confirmation', 'text', 'Reporter-2083!'),
        ('district', 'text', 'kailali'),
        ('experience', 'text', 'स्थानीय एफएममा पाँच वर्ष रिपोर्टिङ। Five years reporting for a local FM station in Dhangadhi.'),
        ('samples[0]', 'text', 'https://example.com/my-story-1'),
        ('samples[1]', 'text', 'https://example.com/my-story-2'),
        ('documents[0]', 'file', PDF['src']),
        ('documents[1]', 'file', PRESS['src']),
    ],
    # --- Me --------------------------------------------------------------------
    'PATCH /v1/me': {'name': 'सुपर एडमिन', 'designation': 'प्रधान सम्पादक', 'bio': 'पश्चिम टुडे, धनगढी', 'preferred_locale': 'ne'},
    'PUT /v1/me/password': {'current_password': '{{password}}', 'password': '{{new_password}}', 'password_confirmation': '{{new_password}}'},
    'POST /v1/me/2fa/confirm': {'code': '{{two_factor_code}}'},
    'PATCH /v1/me/devices/{id}': {'name': 'Postman (office laptop)', 'trusted': True},
    'PUT /v1/me/notification-preferences': {
        'preferences': [
            {'event': 'story_submitted', 'channel': 'mail', 'enabled': False},
            {'event': 'story_published', 'channel': 'push', 'enabled': True},
            {'event': 'sla_breach', 'channel': 'sms', 'enabled': True},
        ],
        'quiet_hours': {'start': '22:00', 'end': '06:00'},
        'daily_digest': True,
    },
    # --- CMS · Users -----------------------------------------------------------
    'POST /v1/cms/users': {'name': {'ne': 'गीता अवस्थी', 'en': 'Geeta Awasthi'}, 'username': 'geeta.awasthi{{$randomInt}}', 'email': 'geeta.{{$timestamp}}@paschimtoday.local', 'password': 'Editor-Desk-2083!', 'type': 'staff', 'role': 'editor', 'preferred_locale': 'ne', 'designation': 'उप-सम्पादक', 'bio': 'राजनीति डेस्क', 'is_verified_reporter': False},
    'PATCH /v1/cms/users/{user}': {'designation': 'वरिष्ठ उप-सम्पादक', 'bio': 'राजनीति तथा संसद बिट', 'preferred_locale': 'ne'},
    'POST /v1/cms/users/{user}/suspend': {'reason': 'Repeated policy violations (test)'},
    'POST /v1/cms/users/{user}/reactivate': {'reason': 'Reviewed and cleared'},
    'POST /v1/cms/users/{user}/force-logout': {'reason': 'Lost phone reported'},
    'POST /v1/cms/users/{user}/reset-2fa': {'reason': 'User changed phone'},
    'POST /v1/cms/invitations': {'email': 'new.editor.{{$timestamp}}@paschimtoday.local', 'role': 'editor', 'name': 'नयाँ सम्पादक', 'scopes': [{'type': 'desk', 'key': 'politics'}]},
    'POST /v1/cms/reporter-applications/{id}/approve': {'role': 'reporter', 'notes': 'Samples verified with the Kailali desk head'},
    'POST /v1/cms/reporter-applications/{id}/reject': {'reason': 'Documents could not be verified'},
    # --- CMS · Access ----------------------------------------------------------
    'PUT /v1/cms/users/{user}/roles': {'roles': ['editor']},
    'POST /v1/cms/users/{user}/permissions': {'permission': 'media.delete', 'effect': 'deny', 'reason': 'Only photo desk may delete media', 'expires_at': '{{in_thirty_days_iso}}'},
    'PUT /v1/cms/users/{user}/scopes': {'scopes': [{'type': 'district', 'key': 'kailali'}, {'type': 'desk', 'key': 'politics'}]},
    'POST /v1/cms/roles': {'name': 'district-coordinator-{{$randomInt}}', 'label': 'District Coordinator', 'description': 'Coordinates stringers in one district', 'requires_2fa': True, 'default_scope': 'district', 'permissions': ['content.stories.view.desk', 'workflow.review', 'workflow.return']},
    'PATCH /v1/cms/roles/{role}': {'label': 'District Coordinator (Far West)', 'description': 'Coordinates stringers in Sudurpaschim districts'},
    'PUT /v1/cms/roles/{role}/permissions': {'permissions': ['content.stories.view.desk', 'workflow.review', 'workflow.return', 'workflow.assign']},
    'POST /v1/cms/desks': {'name': {'ne': 'खेलकुद डेस्क', 'en': 'Sports desk'}, 'slug': 'sports-desk-{{$randomInt}}', 'type': 'beat', 'is_active': True},
    'PATCH /v1/cms/desks/{desk}': {'name': {'ne': 'खेलकुद तथा युवा डेस्क', 'en': 'Sports & youth desk'}, 'is_active': True},
    'PUT /v1/cms/desks/{desk}/members': {'members': ['{{user_uid}}']},
    # --- CMS · Modules ---------------------------------------------------------
    'PATCH /v1/cms/modules/{module}': {'enabled': True, 'surfaces': ['web', 'android', 'ios'], 'audience': {'type': 'districts', 'districts': ['kailali', 'kanchanpur']}, 'cascade': False},
    # --- CMS · Media -----------------------------------------------------------
    'POST /v1/cms/media/init-upload': {'name': 'sample-photo.jpg', 'mime': 'image/jpeg', 'size': PHOTO['size'], 'sha256': PHOTO['sha256']},
    'POST /v1/cms/media/uploads/{upload}/chunk': [('number', 'text', '0'), ('file', 'file', PHOTO['src'])],
    'POST /v1/cms/media/embeds': {'url': 'https://www.youtube.com/watch?v=dQw4w9WgXcQ', 'title': 'सेती नदीको भिडियो'},
    'POST /v1/cms/media/folders': {'name': 'बाढी २०८३', 'parent': None},
    'PATCH /v1/cms/media/folders/{folder}': {'name': 'बाढी २०८३ — कैलाली', 'parent': None},
    'PATCH /v1/cms/media/{asset}': {'title': 'सेती नदी', 'caption': 'धनगढी नजिक सेती नदीको बढ्दो बहाव', 'alt': 'Swollen Seti river near Dhangadhi', 'credit': 'पश्चिम टुडे', 'licence': 'All rights reserved', 'folder': '{{folder_uid}}', 'tags': ['बाढी', 'कैलाली'], 'focal_point': {'x': 0.5, 'y': 0.4}},
    'POST /v1/cms/media/{asset}/crop': {'x': 0.1, 'y': 0.1, 'width': 0.8, 'height': 0.6},
    'POST /v1/cms/media/{asset}/replace': {'name': 'sample-photo.jpg', 'mime': 'image/jpeg', 'size': PHOTO['size'], 'sha256': PHOTO['sha256']},
    # --- CMS · Stories ---------------------------------------------------------
    'POST /v1/cms/stories': STORY,
    'PATCH /v1/cms/stories/{story}': STORY_UPDATE,
    'POST /v1/cms/stories/{story}/autosave': {**STORY_UPDATE, 'reason': 'Autosave'},
    'POST /v1/cms/stories/{story}/revisions/{revision}/restore': {'reason': 'Restore the original headline'},
    # --- CMS · Taxonomy --------------------------------------------------------
    'POST /v1/cms/categories': {'name': {'ne': 'सुदूरपश्चिम', 'en': 'Sudurpaschim'}, 'slug': 'sudurpaschim-{{$randomInt}}', 'is_active': True, 'sort_order': 5, 'seo': TAXON_SEO, 'color': '#b91c1c', 'icon': 'map', 'layout_key': 'default', 'show_in_menu': True},
    'PATCH /v1/cms/categories/{term}': {'name': {'ne': 'सुदूरपश्चिम प्रदेश', 'en': 'Sudurpaschim Province'}, 'sort_order': 6, 'show_in_menu': True},
    'PUT /v1/cms/categories/reorder': {'parent': None, 'categories': '@@category_order@@'},
    'POST /v1/cms/tags': {'name': {'ne': 'बाढी', 'en': 'Flood'}, 'slug': 'flood-{{$randomInt}}', 'is_active': True, 'seo': TAXON_SEO},
    'PATCH /v1/cms/tags/{term}': {'name': {'ne': 'बाढी पहिरो', 'en': 'Floods and landslides'}},
    'POST /v1/cms/tags/{term}/merge': {'target': '{{tag_merge_target_uid}}'},
    'POST /v1/cms/topics': {'name': {'ne': 'मनसुन २०८३', 'en': 'Monsoon 2083'}, 'slug': 'monsoon-2083-{{$randomInt}}', 'is_active': True, 'seo': TAXON_SEO},
    'PATCH /v1/cms/topics/{term}': {'name': {'ne': 'मनसुन २०८३ — सुदूरपश्चिम', 'en': 'Monsoon 2083 — Far West'}},
    'POST /v1/cms/entities': {'name': {'ne': 'धनगढी उपमहानगरपालिका', 'en': 'Dhangadhi Sub-Metropolitan City'}, 'slug': 'dhangadhi-submetro-{{$randomInt}}', 'type': 'organisation', 'is_active': True},
    'PATCH /v1/cms/entities/{term}': {'name': {'ne': 'धनगढी उपमहानगरपालिका कार्यालय', 'en': 'Dhangadhi Sub-Metropolitan City Office'}, 'type': 'organisation'},
    # --- CMS · Workflow --------------------------------------------------------
    'POST /v1/cms/stories/{story}/assign': {'assignee': '{{editor_uid}}', 'desk': '{{desk_uid}}', 'deadline': FUTURE, 'instructions': 'प्रमुख जिल्ला अधिकारीसँग पुष्टि गर्नुहोस्। Confirm figures with the CDO.', 'reason': 'Needs desk verification'},
    'POST /v1/cms/stories/{story}/priority': {'priority': 'P1', 'reason': 'Police confirmed three people missing'},
    'POST /v1/cms/duty-shifts': {'user': '{{editor_uid}}', 'role': 'editor', 'starts_at': '{{now_iso}}', 'ends_at': '{{in_eight_hours_iso}}', 'type': 'day'},
    'PATCH /v1/cms/duty-shifts/{shift}': {'user': '{{editor_uid}}', 'role': 'editor', 'starts_at': '{{now_iso}}', 'ends_at': '{{in_twelve_hours_iso}}', 'type': 'night'},
    # --- CMS · Workflow configuration -------------------------------------------
    'PATCH /v1/cms/workflow/settings': {'key': 'editor_can_publish', 'value': True, 'scope_type': 'global', 'base_version': '{{setting_base_version}}', 'is_active': True, 'reason': 'Trusted editors may publish directly'},
}

# Extra named requests for the same endpoint (story transition examples).
TRANSITIONS = [
    ('Transition · submit (P2)', {'action': 'submit', 'priority': 'P2'}, 'Reporter submits the draft to the queue. P0 needs priority_reason.'),
    ('Transition · submit as P0 flash', {'action': 'submit', 'priority': 'P0', 'priority_reason': 'Earthquake felt across Doti and Achham'}, 'P0 alerts on-duty reviewers immediately (critical queue).'),
    ('Transition · assign_editor', {'action': 'assign_editor', 'assignee': '{{editor_uid}}', 'deadline': FUTURE, 'instructions': 'Verify casualty numbers', 'relevance': 4, 'notes': 'Strong local angle'}, 'Leave assignee out to use the auto_assign setting.'),
    ('Transition · publish_as_is', {'action': 'publish_as_is', 'relevance': 4, 'notes': 'Clean copy'}, 'relevance (1–5) is required on the first review action.'),
    ('Transition · edit_and_publish', {'action': 'edit_and_publish', 'relevance': 5, 'reason': 'Tightened headline', 'content': {'headline': {'ne': 'धनगढीमा भारी वर्षा, सेती खतराको तहमा', 'en': 'Seti reaches danger level after Dhangadhi downpour'}}}, 'Edits the content and publishes in one step.'),
    ('Transition · return_to_reporter', {'action': 'return_to_reporter', 'reason': 'कृपया प्रहरीको आधिकारिक भनाइ थप्नुहोस्।', 'relevance': 3}, 'Returns the story with a reason; the reporter is notified.'),
    ('Transition · reject', {'action': 'reject', 'reason': 'Could not be verified', 'rejection_reason': 'fake_fabricated', 'relevance': 1}, 'rejection_reason keys: duplicate, fake_fabricated, incomplete, legal_risk, misleading, not_newsworthy, other, out_of_beat, plagiarised, poor_quality.'),
    ('Transition · schedule', {'action': 'schedule', 'scheduled_at': FUTURE, 'relevance': 4}, 'Publishes automatically at scheduled_at (workflow:publish-scheduled).'),
    ('Transition · send_for_verification (editor)', {'action': 'send_for_verification', 'relevance': 4}, 'Assigned editor sends the story back for admin verification.'),
    ('Transition · editor_publish (editor)', {'action': 'editor_publish', 'relevance': 4}, 'Only offered when the editor_can_publish setting is on (or P0 fast-track).'),
    ('Transition · hold', {'action': 'hold', 'reason': 'Waiting for official statement', 'relevance': 3}, ''),
]

# Extra requests inserted after an endpoint: (name, body, capture lines, description).
EXTRA_AFTER = {
    'POST /v1/cms/tags': [('Create second tag (merge target)', {'name': {'ne': 'पहिरो', 'en': 'Landslide'}, 'slug': 'landslide-{{$randomInt}}', 'is_active': True},
                           ["save('tag_merge_target_uid', idOf(j.data));"], 'Merge tag merges *Create tag* into this one.')],
}

# Path parameter → variable.
PATH_VARS = {
    'user': 'user_uid', 'story': 'story_uid', 'role': 'role_name', 'desk': 'desk_uid', 'module': 'module_key',
    'permission': 'permission_name', 'upload': 'upload_uid', 'asset': 'asset_uid', 'folder': 'folder_uid',
    'revision': 'revision_number', 'template': 'template_uid', 'setting': 'setting_uid', 'shift': 'shift_uid',
    'token': 'invitation_token', 'slug': 'story_slug',
    'export': 'analytics_export_uid', 'alert': 'analytics_alert_uid', 'flag': 'accuracy_flag_uid', 'appeal': 'scorecard_appeal_uid',
}


def path_var(path, name):
    if '/analytics/' in path or '/scorecards/' in path:
        if name == 'type':
            return 'analytics_location_type'
        if name == 'slug':
            return 'analytics_location_slug'
        if name == 'category':
            return 'category_uid'
        if name == 'key':
            return 'analytics_rule_key'
    if name == 'uid' and path.endswith('/counts'):
        return 'story_uid'
    if name == 'term':
        for kind, var in (('categories', 'category_term_uid'), ('tags', 'tag_uid'), ('topics', 'topic_uid'), ('entities', 'entity_uid')):
            if '/' + kind + '/' in path:
                return var
    if name == 'id':
        if 'reporter-applications' in path:
            return 'application_uid'
        if 'devices' in path:
            return 'device_uid'
        if 'notifications' in path:
            return 'notification_id'
    if name == 'version':
        return 'setting_version' if '/settings/' in path else 'template_version'
    if name == 'story' and 'story-preview' in path:
        return 'story_uid'
    return PATH_VARS.get(name, name)


QUERY_VALUES = {
    'filter[status]': 'submitted', 'filter[priority]': 'P1', 'filter[category]': '{{category_uid}}', 'filter[district]': 'kailali',
    'filter[desk]': '{{desk_uid}}', 'filter[language]': 'ne', 'filter[content_type]': 'news', 'filter[type]': 'staff',
    'filter[role]': 'editor', 'filter[search]': 'joshi', 'filter[is_verified_reporter]': '1', 'filter[slug]': 'national',
    'filter[is_active]': '1', 'filter[parent]': '{{category_uid}}', 'filter[show_in_menu]': '1', 'filter[folder]': '{{folder_uid}}',
    'filter[uploader]': '{{user_uid}}', 'filter[tag]': 'बाढी', 'filter[from]': '2026-11-01', 'filter[to]': '2026-11-30',
    'filter[key]': 'admin-approves-everything', 'filter[is_default]': '1', 'sort': '-created_at', 'per_page': '25', 'page': '1',
    'province': 'sudurpaschim', 'district': 'kailali', 'local_level': 'dhangadhi', 'surface': 'web', 'ad': '2026-11-27', 'bs': '2083-08-11',
    'status': 'submitted', 'priority': 'P0', 'desk': '{{desk_uid}}', 'assignee': '{{editor_uid}}', 'unread': '1', 'cursor': '',
    'from': '1', 'to': '2', 'code': '{{totp}}', 'reason': 'Grant no longer needed', 'template': '{{template_uid}}', 'user': '{{user_uid}}',
    'category': '{{category_uid}}',
}
# Optional query parameters switched on by default (others are present but disabled).
QUERY_ON_PATHS = {
    '/v1/public/geo/districts': {'province'}, '/v1/public/geo/local-levels': {'district'}, '/v1/public/calendar/convert': {'ad'},
    '/v1/cms/categories': {'filter[slug]'}, '/v1/cms/users/{user}/permissions/{permission}': {'reason'},
}
# Requests whose URL is a signed link returned by an earlier request.
SIGNED = {'GET /v1/public/story-preview/{story}': ('preview_url', 'Run *CMS · Stories → Preview token* first; this calls the signed URL it returned.'),
          'GET /v1/cms/media/{asset}/original': ('original_url', 'Run *Download original* first; this calls the signed URL it returned (valid 5 minutes).')}

# Test scripts that capture values for the next requests.
CAPTURE = {
    'POST /v1/cms/analytics/exports': ["save('analytics_export_uid', idOf(j.data));"],
    'GET /v1/cms/analytics/alerts': ["save('analytics_alert_uid', idOf(first(j)));"],
    'POST /v1/cms/stories/{story}/accuracy-flags': ["save('accuracy_flag_uid', idOf(j.data));"],
    'POST /v1/cms/scorecards/appeals': ["save('scorecard_appeal_uid', idOf(j.data));"],
    'POST /v1/auth/login': ["if (j.data && j.data.challenge_token) save('challenge_token', j.data.challenge_token);", 'saveTokens(j);'],
    'POST /v1/auth/2fa/challenge': ['saveTokens(j);', "if (pm.response.code === 200) { pm.collectionVariables.set('email_code', ''); if (pm.environment.name) pm.environment.set('email_code', ''); }"],
    'POST /v1/auth/refresh': ['saveTokens(j);'],
    'POST /v1/auth/otp/verify': ['saveTokens(j);'],
    'POST /v1/auth/login/otp': ['saveTokens(j);'],
    'POST /v1/auth/invitations/accept': ['saveTokens(j);'],
    'POST /v1/me/2fa/enable': ["save('totp_secret', j.data && j.data.secret);"],
    'POST /v1/me/2fa/confirm': ["if (pm.response.code === 200) { pm.collectionVariables.set('email_code', ''); if (pm.environment.name) pm.environment.set('email_code', ''); }"],
    'GET /v1/me/devices': ["save('device_uid', idOf(first(j)));"],
    'GET /v1/me/notifications': ["save('notification_id', first(j) && first(j).id);"],
    'POST /v1/cms/users': ["save('user_uid', idOf(j.data)); save('editor_uid', idOf(j.data));"],
    'GET /v1/cms/users': ["save('user_uid', idOf(first(j)));"],
    'POST /v1/cms/roles': ["save('role_name', j.data && j.data.name);"],
    'GET /v1/cms/desks': ["save('desk_uid', idOf(first(j)));"],
    'POST /v1/cms/desks': ["save('desk_uid', idOf(j.data));"],
    'GET /v1/cms/reporter-applications': ["save('application_uid', idOf(first(j)));"],
    'POST /v1/cms/invitations': ["save('invitation_uid', idOf(j.data));"],
    'GET /v1/cms/categories': ["save('category_uid', idOf(first(j)));"],
    'POST /v1/cms/categories': ["save('category_term_uid', idOf(j.data));"],
    'GET /v1/cms/categories/tree': ["// Complete root sibling group, reversed, for Reorder categories.", "if (Array.isArray(j.data)) save('category_order', JSON.stringify(j.data.map(idOf).reverse()));"],
    'POST /v1/cms/tags': ["save('tag_uid', idOf(j.data));"],
    'POST /v1/cms/topics': ["save('topic_uid', idOf(j.data));"],
    'POST /v1/cms/entities': ["save('entity_uid', idOf(j.data));"],
    'POST /v1/cms/media/init-upload': ["save('upload_uid', idOf(j.data)); save('asset_uid', j.data && j.data.asset && j.data.asset.uid);"],
    'POST /v1/cms/media/embeds': ["save('embed_asset_uid', idOf(j.data));"],
    'POST /v1/cms/media/folders': ["save('folder_uid', idOf(j.data));"],
    'POST /v1/cms/media/{asset}/download-original': ["save('original_url', j.data && j.data.url);"],
    'POST /v1/cms/stories': ["save('story_uid', idOf(j.data));"],
    'GET /v1/cms/stories': ["if (!pm.collectionVariables.get('story_uid')) save('story_uid', idOf(first(j)));"],
    'POST /v1/cms/stories/{story}/preview-token': ["save('preview_url', j.data && j.data.url);"],
    'POST /v1/cms/duty-shifts': ["save('shift_uid', idOf(j.data));"],
    'GET /v1/cms/workflow/templates': ["save('template_uid', idOf(first(j))); save('template_version', first(j) && first(j).version);"],
    'POST /v1/cms/workflow/templates': ["save('template_uid', idOf(j.data)); save('template_version', j.data && j.data.version);"],
    'PATCH /v1/cms/workflow/settings': [
        "save('setting_uid', idOf(j.data)); save('setting_version', j.data && j.data.version); save('setting_base_version', j.data && j.data.version);",
        "// 409 = someone saved first: keep their version so the next Send succeeds.",
        "if (pm.response.code === 409 && j.error && j.error.details) save('setting_base_version', j.error.details.current_version);",
    ],
    'PATCH /v1/cms/workflow/templates/{template}': ["save('template_version', j.data && j.data.version);"],
}

# Folder order (by OpenAPI tag) and request order inside folders.
FOLDERS = ['Auth', 'Me', 'CMS · Users', 'CMS · Access', 'CMS · Taxonomy', 'CMS · Media', 'CMS · Stories', 'CMS · Workflow',
           'CMS · Workflow configuration', 'CMS · Modules', 'Public · Geo & calendar', 'Public · Stories', 'Public · Config', 'System']
FOLDER_INFO = {
    'Finish (run last)': '',
    'Auth': '**2FA by e-mail** (TWO_FACTOR_METHOD=email): Login e-mails a 6-digit code — paste it into `email_code`, then run **2FA challenge** (*Resend* sends a new one). For dangerous actions later: *Me → Send 2FA e-mail code* → paste → *Me → Confirm 2FA*. With an authenticator, leave `email_code` empty and set `totp_secret`. Locally mail and SMS go to the log (MAIL_MAILER=log, SMS_DRIVER=log): copy OTP codes, reset and invitation tokens from storage/logs into `otp_code`, `password_reset_token`, `invitation_token`. Auth routes are rate-limited — wait for `retry_after` on 429. Start here: **Login** → (if `two_factor_required`) **2FA challenge**. Tokens are saved automatically. Super-admin, system-admin, desk-head and editor need 2FA for every CMS call: if login says `two_factor_enrollment_required`, run *Me → Enable 2FA* then *Me → Confirm 2FA*.',
    'CMS · Stories': 'Run **Create story** first: it saves `story_uid`. Needs `category_uid` — run *CMS · Taxonomy → List categories* (filter[slug]=national) once.',
    'CMS · Workflow': 'Transition examples are alternatives — pick the one that matches the story\'s current status (see **Available actions**).',
    'CMS · Media': 'Chunked upload: **Init upload** → **Upload chunk** (multipart, file = fixtures/sample-photo.jpg) → **Complete upload**. The size and sha256 in Init upload match the fixture file.',
}
ORDER_HINTS = [
    # Auth
    '/v1/auth/login', '/v1/auth/2fa/challenge', '/v1/auth/2fa/challenge/resend', '/v1/auth/refresh', '/v1/auth/otp/send', '/v1/auth/otp/verify', '/v1/auth/login/otp',
    '/v1/auth/register', '/v1/auth/register/reporter', '/v1/auth/password/forgot', '/v1/auth/password/reset', '/v1/auth/invitations/{token}',
    '/v1/auth/invitations/accept',
    # Me
    '/v1/me', '/v1/me/permissions', '/v1/me/2fa/email-code', '/v1/me/2fa/enable', '/v1/me/2fa/confirm', '/v1/me/2fa/recovery-codes', '/v1/me/devices', '/v1/me/devices/{id}',
    '/v1/me/notifications', '/v1/me/notifications/{id}/read', '/v1/me/notifications/read-all', '/v1/me/notification-preferences',
    # Taxonomy: list categories first so category_uid is set
    '/v1/cms/categories', '/v1/cms/categories/tree', '/v1/cms/categories/{term}', '/v1/cms/categories/reorder',
    '/v1/cms/tags', '/v1/cms/tags/{term}', '/v1/cms/tags/{term}/merge', '/v1/cms/topics', '/v1/cms/topics/{term}', '/v1/cms/entities', '/v1/cms/entities/{term}',
    # Media
    '/v1/cms/media/init-upload', '/v1/cms/media/uploads/{upload}/chunk', '/v1/cms/media/uploads/{upload}/complete', '/v1/cms/media/uploads/{upload}',
    '/v1/cms/media/folders', '/v1/cms/media/folders/{folder}', '/v1/cms/media', '/v1/cms/media/{asset}', '/v1/cms/media/embeds',
    # Stories
    '/v1/cms/stories', '/v1/cms/stories/{story}', '/v1/cms/stories/{story}/autosave', '/v1/cms/stories/{story}/heartbeat',
    '/v1/cms/stories/{story}/revisions', '/v1/cms/stories/{story}/diff', '/v1/cms/stories/{story}/revisions/{revision}/restore',
    '/v1/cms/stories/{story}/preview-token', '/v1/cms/stories/{story}/contributions', '/v1/cms/stories/{story}/lock/override', '/v1/cms/stories/{story}/lock',
    # Workflow
    '/v1/cms/stories/{story}/actions', '/v1/cms/stories/{story}/transition', '/v1/cms/stories/{story}/history', '/v1/cms/queues',
    '/v1/cms/stories/{story}/assign', '/v1/cms/stories/{story}/priority', '/v1/cms/duty-shifts', '/v1/cms/duty-shifts/{shift}',
    # Users / access
    '/v1/cms/users', '/v1/cms/users/{user}', '/v1/cms/invitations', '/v1/cms/reporter-applications',
    '/v1/cms/roles', '/v1/cms/roles/{role}', '/v1/cms/roles/{role}/permissions', '/v1/cms/desks', '/v1/cms/desks/{desk}',
]
METHOD_ORDER = {'GET': 1, 'POST': 0, 'PUT': 2, 'PATCH': 2, 'DELETE': 9}
LIST_FIRST = {'/v1/cms/categories', '/v1/cms/desks', '/v1/cms/workflow/templates', '/v1/cms/users', '/v1/me/devices', '/v1/me/notifications', '/v1/cms/media/folders'}
LAST = ['POST /v1/auth/logout', 'PUT /v1/me/password', 'DELETE /v1/me/2fa', 'POST /v1/cms/users/{user}/force-logout', 'POST /v1/cms/users/{user}/reset-2fa',
        'POST /v1/cms/users/{user}/suspend', 'POST /v1/cms/users/{user}/reactivate', 'POST /v1/cms/stories/{story}/lock/override',
        'DELETE /v1/cms/stories/{story}/lock', 'DELETE /v1/cms/stories/{story}']

NAMES = {
    'POST /v1/auth/login': 'Login (username / email / phone)', 'POST /v1/auth/2fa/challenge': '2FA challenge (email code or TOTP)', 'POST /v1/auth/2fa/challenge/resend': 'Resend 2FA e-mail code',
    'POST /v1/me/2fa/email-code': 'Send 2FA e-mail code (step-up)',
    'POST /v1/auth/refresh': 'Refresh tokens', 'POST /v1/auth/logout': 'Logout', 'POST /v1/me/2fa/enable': 'Enable 2FA (saves totp_secret)',
    'POST /v1/me/2fa/confirm': 'Confirm 2FA / step-up for dangerous actions', 'POST /v1/cms/stories': 'Create story',
    'POST /v1/cms/media/uploads/{upload}/chunk': 'Upload chunk (multipart)', 'POST /v1/auth/register/reporter': 'Register reporter (multipart with documents)',
    'POST /v1/cms/media/init-upload': 'Init upload (sample-photo.jpg)', 'POST /v1/cms/media/uploads/{upload}/complete': 'Complete upload',
    'GET /v1/cms/media/uploads/{upload}': 'Upload status', 'GET /v1/cms/media/folders': 'List folders', 'POST /v1/cms/media/folders': 'Create folder',
    'PATCH /v1/cms/media/folders/{folder}': 'Rename / move folder', 'GET /v1/cms/media': 'List media library', 'GET /v1/cms/media/{asset}': 'Show asset',
    'PATCH /v1/cms/media/{asset}': 'Update asset metadata', 'POST /v1/cms/media/embeds': 'Create embed (YouTube)', 'POST /v1/cms/media/{asset}/crop': 'Crop asset',
    'POST /v1/cms/media/{asset}/replace': 'Replace file (starts a new upload)', 'POST /v1/cms/media/{asset}/download-original': 'Download original (signed link)',
    'GET /v1/cms/media/{asset}/original': 'Open original (signed link)',
    'GET /v1/cms/stories': 'List stories', 'GET /v1/cms/stories/{story}': 'Show story', 'PATCH /v1/cms/stories/{story}': 'Update story',
    'DELETE /v1/cms/stories/{story}': 'Delete story', 'POST /v1/cms/stories/{story}/autosave': 'Autosave story', 'POST /v1/cms/stories/{story}/heartbeat': 'Edit-lock heartbeat',
    'POST /v1/cms/stories/{story}/lock/override': 'Override edit lock', 'DELETE /v1/cms/stories/{story}/lock': 'Release edit lock',
    'GET /v1/cms/stories/{story}/revisions': 'List revisions', 'GET /v1/cms/stories/{story}/diff': 'Diff two revisions',
    'POST /v1/cms/stories/{story}/revisions/{revision}/restore': 'Restore revision', 'POST /v1/cms/stories/{story}/preview-token': 'Preview token (signed link)',
    'GET /v1/cms/stories/{story}/contributions': 'Contributions', 'GET /v1/cms/stories/{story}/actions': 'Available actions',
    'GET /v1/cms/stories/{story}/history': 'Story history (every transition)', 'GET /v1/public/stories/{slug}': 'Public story by slug',
    'GET /v1/public/story-preview/{story}': 'Story preview (signed link)',
    'GET /v1/cms/categories': 'List categories (saves category_uid)', 'POST /v1/cms/categories': 'Create category', 'GET /v1/cms/categories/tree': 'Category tree',
    'GET /v1/cms/categories/{term}': 'Show category', 'PATCH /v1/cms/categories/{term}': 'Update category', 'DELETE /v1/cms/categories/{term}': 'Delete category',
    'PUT /v1/cms/categories/reorder': 'Reorder categories', 'GET /v1/cms/tags': 'List tags', 'POST /v1/cms/tags': 'Create tag', 'GET /v1/cms/tags/{term}': 'Show tag',
    'PATCH /v1/cms/tags/{term}': 'Update tag', 'DELETE /v1/cms/tags/{term}': 'Delete tag', 'POST /v1/cms/tags/{term}/merge': 'Merge tag (create two tags first)',
    'GET /v1/cms/topics': 'List topics', 'POST /v1/cms/topics': 'Create topic', 'GET /v1/cms/topics/{term}': 'Show topic', 'PATCH /v1/cms/topics/{term}': 'Update topic',
    'DELETE /v1/cms/topics/{term}': 'Delete topic', 'GET /v1/cms/entities': 'List entities', 'POST /v1/cms/entities': 'Create entity',
    'GET /v1/cms/entities/{term}': 'Show entity', 'PATCH /v1/cms/entities/{term}': 'Update entity', 'DELETE /v1/cms/entities/{term}': 'Delete entity',
    'GET /v1/cms/workflow/templates': 'List workflow templates', 'POST /v1/cms/workflow/templates': 'Create workflow template',
    'GET /v1/cms/workflow/templates/{template}': 'Show workflow template', 'PATCH /v1/cms/workflow/templates/{template}': 'Update workflow template (new version)',
    'GET /v1/cms/workflow/templates/{template}/versions/{version}': 'Workflow template version', 'GET /v1/cms/workflow/settings': 'Effective workflow settings',
    'PATCH /v1/cms/workflow/settings': 'Save workflow setting (editor_can_publish)', 'GET /v1/cms/workflow/settings/{setting}/versions/{version}': 'Workflow setting version',
}


# ---------------------------------------------------------------------------
# Schema fallback
# ---------------------------------------------------------------------------
def resolve(s):
    seen = 0
    while isinstance(s, dict) and '$ref' in s and seen < 20:
        s = schemas[s['$ref'].split('/')[-1]]
        seen += 1
    return s


def example(s, name='', depth=0):
    s = resolve(s)
    if depth > 4 or not isinstance(s, dict):
        return None
    if 'example' in s:
        return s['example']
    if 'allOf' in s:
        out = {}
        for part in s['allOf']:
            v = example(part, name, depth)
            if isinstance(v, dict):
                out.update(v)
        return out
    for key in ('anyOf', 'oneOf'):
        if key in s:
            return example(next((x for x in s[key] if resolve(x).get('type') != 'null'), s[key][0]), name, depth)
    if 'enum' in s:
        return next((e for e in s['enum'] if e is not None), None)
    t = s.get('type')
    if isinstance(t, list):
        t = next((x for x in t if x != 'null'), 'string')
    if t == 'object' or 'properties' in s:
        return {k: example(v, k, depth + 1) for k, v in s.get('properties', {}).items()}
    if t == 'array':
        item = example(s.get('items', {}), name, depth + 1)
        return [item] if item is not None else []
    if t == 'integer':
        return 1
    if t == 'number':
        return 0.5
    if t == 'boolean':
        return True
    fmt = s.get('format')
    if fmt == 'date-time':
        return FUTURE
    if fmt == 'email':
        return 'test@example.com'
    if fmt == 'uri':
        return 'https://example.com'
    if 'reason' in name:
        return 'Test from Postman'
    return 'परीक्षण'


# ---------------------------------------------------------------------------
# Postman building
# ---------------------------------------------------------------------------
def url(path, op):
    raw_path = re.sub(r'\{(\w+)\}', lambda m: '{{' + path_var(path, m.group(1)) + '}}', path)
    query = []
    for p in op.get('parameters', []):
        if p.get('in') != 'query':
            continue
        name = p['name']
        on = p.get('required', False) or name in QUERY_ON_PATHS.get(path, set())
        q = {'key': name, 'value': QUERY_VALUES.get(name, ''), 'description': (resolve(p.get('schema', {})).get('description') or p.get('description') or '')[:300]}
        if '/analytics/' in path or '/scorecards' in path:
            q['value'] = {'from': '2026-11-01', 'to': '2026-11-30', 'compare_from': '2026-10-01', 'compare_to': '2026-10-30', 'dimension': 'site' if path.endswith('/compare') else 'story', 'period': '30d', 'metric': 'views', 'role': 'reporter', 'sort': 'credibility', 'status': 'pending'}.get(name, q['value'])
        if not on:
            q['disabled'] = True
        query.append(q)
    raw = '{{base_url}}' + raw_path
    enabled = [q for q in query if not q.get('disabled')]
    if enabled:
        raw += '?' + '&'.join(f"{q['key']}={q['value']}" for q in enabled)
    out = {'raw': raw, 'host': ['{{base_url}}'], 'path': [x for x in raw_path.strip('/').split('/')]}
    if query:
        out['query'] = query
    return out


def body_for(key, op):
    rb = op.get('requestBody')
    if key in BODIES:
        data = BODIES[key]
    elif rb:
        content = rb.get('content', {})
        ctype = 'multipart/form-data' if 'multipart/form-data' in content else next(iter(content), 'application/json')
        data = example(content[ctype]['schema'])
        if ctype == 'multipart/form-data' and isinstance(data, dict):
            data = [(k, 'text', json.dumps(v, ensure_ascii=False) if isinstance(v, (dict, list)) else str(v)) for k, v in data.items()]
    else:
        return None
    if isinstance(data, list):
        form = []
        for k, kind, v in data:
            if kind == 'file':
                form.append({'key': k, 'type': 'file', 'src': v, 'description': 'Choose a file (fixture in docs/postman/fixtures/)'})
            else:
                form.append({'key': k, 'type': 'text', 'value': v})
        return {'mode': 'formdata', 'formdata': form}
    raw = re.sub(r'"@@(\w+)@@"', r'{{\1}}', json.dumps(data, ensure_ascii=False, indent=2))
    return {'mode': 'raw', 'raw': raw, 'options': {'raw': {'language': 'json'}}}


def test_script(key, extra=None):
    lines = [
        "const save = (k, v) => { if (v === undefined || v === null || v === '') return; pm.collectionVariables.set(k, String(v)); if (pm.environment.name) pm.environment.set(k, String(v)); };",
        "const first = (j) => Array.isArray(j.data) ? j.data[0] : undefined;",
        "const idOf = (o) => o ? (o.uid || o.id) : undefined;",
        "const saveTokens = (j) => { const d = j.data || {}; save('access_token', d.access_token); save('refresh_token', d.refresh_token); };",
        "let j = {}; try { j = pm.response.json(); } catch (e) {}",
        "pm.test('status is 2xx', () => pm.expect(pm.response.code).to.be.within(200, 299));",
    ]
    lines += CAPTURE.get(key, []) + (extra or [])
    return [{'listen': 'test', 'script': {'type': 'text/javascript', 'exec': lines}}]


def request_item(name, method, path, op, body=None, description=None, key=None):
    key = key or f'{method} {path}'
    headers = [{'key': 'Accept', 'value': 'application/json'}, {'key': 'Accept-Language', 'value': '{{locale}}'}]
    req = {'method': method, 'header': headers, 'url': url(path, op)}
    if key in SIGNED:
        var, note = SIGNED[key]
        req['url'] = {'raw': '{{' + var + '}}'}
        description = ((description or '') + ' ' + note).strip()
    desc = []
    if op.get('summary'):
        desc.append('**' + op['summary'] + '**')
    if op.get('description'):
        desc.append(op['description'])
    if description:
        desc.append(description)
    if desc:
        req['description'] = '\n\n'.join(desc)
    b = body if body is not None else body_for(key, op)
    if b:
        req['body'] = b
        if b['mode'] == 'raw':
            headers.append({'key': 'Content-Type', 'value': 'application/json'})
    if op.get('security') == []:
        req['auth'] = {'type': 'noauth'}
    return {'name': name, 'event': test_script(key), 'request': req}


def nice_name(method, path, op):
    key = f'{method} {path}'
    if key in NAMES:
        return NAMES[key]
    s = op.get('summary') or ''
    if s:
        return s.rstrip('.')[:80]
    return f'{method} {path.replace("/v1/", "")}'


def sort_key(method, path):
    key = f'{method} {path}'
    if key in LAST:
        return (2, LAST.index(key), 0)
    idx = ORDER_HINTS.index(path) if path in ORDER_HINTS else 500
    m = METHOD_ORDER[method]
    if path in LIST_FIRST and method == 'GET':
        m = -1
    return (1 if method == 'DELETE' else 0, idx, m)


workflow_templates = None
if WORKFLOWS_JSON and os.path.exists(WORKFLOWS_JSON):
    workflow_templates = json.load(open(WORKFLOWS_JSON, encoding='utf-8'))

folders = {}
for path, ops in spec['paths'].items():
    for method, op in ops.items():
        if method not in ('get', 'post', 'put', 'patch', 'delete'):
            continue
        M = method.upper()
        tag = (op.get('tags') or ['Other'])[0]
        folders.setdefault(tag, []).append((M, path, op))

if workflow_templates:
    base = workflow_templates.get('small-newsroom') or next(iter(workflow_templates.values()))
    tpl = {k: base[k] for k in ('name', 'content_types', 'is_default', 'defaults', 'statuses', 'transitions')}
    tpl['name'] = {'ne': 'परीक्षण न्युजरुम', 'en': 'Test newsroom'}
    tpl['content_types'] = []
    tpl['is_default'] = False
    BODIES['POST /v1/cms/workflow/templates'] = {**tpl, 'key': 'test-newsroom-{{$timestamp}}', 'reason': 'Trial workflow from Postman'}
    BODIES['PATCH /v1/cms/workflow/templates/{template}'] = {**tpl, 'base_version': '{{template_version}}', 'reason': 'Add a note to the trial workflow'}

# Requests that end the session or change the login: kept in a last folder so a full
# collection run does not lock itself out half-way.
FINISH = ['POST /v1/auth/refresh', 'PUT /v1/me/password', 'DELETE /v1/me/2fa', 'DELETE /v1/me/devices/{id}', 'POST /v1/auth/logout']
finish = {}

items = []
for tag in FOLDERS + sorted(t for t in folders if t not in FOLDERS):
    if tag not in folders:
        continue
    entries = sorted(folders[tag], key=lambda e: sort_key(e[0], e[1]))
    children = []
    for M, path, op in entries:
        if f'{M} {path}' == 'POST /v1/cms/stories/{story}/transition':
            for tname, tbody, tdesc in TRANSITIONS:
                b = {'mode': 'raw', 'raw': json.dumps(tbody, ensure_ascii=False, indent=2), 'options': {'raw': {'language': 'json'}}}
                children.append(request_item(tname, M, path, op, body=b, description=tdesc))
            continue
        if f'{M} {path}' in FINISH:
            finish[f'{M} {path}'] = request_item(nice_name(M, path, op), M, path, op)
            continue
        children.append(request_item(nice_name(M, path, op), M, path, op))
        for xname, xbody, xcapture, xdesc in EXTRA_AFTER.get(f'{M} {path}', []):
            CAPTURE[f'{M} {path} · {xname}'] = xcapture
            b = {'mode': 'raw', 'raw': json.dumps(xbody, ensure_ascii=False, indent=2), 'options': {'raw': {'language': 'json'}}}
            children.append(request_item(xname, M, path, op, body=b, description=xdesc, key=f'{M} {path} · {xname}'))
    folder = {'name': tag, 'item': children}
    if tag in FOLDER_INFO:
        folder['description'] = FOLDER_INFO[tag]
    items.append(folder)
if finish:
    items.append({'name': 'Finish (run last)', 'description': 'Refresh tokens, change password, disable 2FA and log out. Run these last: a refreshed token starts without the 2FA step-up, the others end the session. Set `new_password` before *Change password*.',
                  'item': [finish[k] for k in FINISH if k in finish]})

PRE_REQUEST = r"""
// Collection pre-request: dates, a unique story slug and the TOTP code ({{totp}}).
const iso = (ms) => new Date(Date.now() + ms).toISOString();
pm.variables.set('now_iso', iso(60 * 1000));
pm.variables.set('tomorrow_iso', iso(24 * 3600 * 1000));
pm.variables.set('in_two_days_iso', iso(48 * 3600 * 1000));
pm.variables.set('in_eight_hours_iso', iso(8 * 3600 * 1000));
pm.variables.set('in_twelve_hours_iso', iso(12 * 3600 * 1000));
pm.variables.set('in_thirty_days_iso', iso(30 * 24 * 3600 * 1000));
if (!pm.collectionVariables.get('story_slug') || pm.info.requestName === 'Create story') {
  pm.collectionVariables.set('story_slug', 'dhangadhi-rain-' + Date.now());
}
if (!pm.collectionVariables.get('device_id')) {
  pm.collectionVariables.set('device_id', 'postman-' + Math.random().toString(36).slice(2, 10));
}

const secret = (pm.environment.get('totp_secret') || pm.collectionVariables.get('totp_secret') || '').replace(/\s|=/g, '').toUpperCase();
const emailCode = pm.environment.get('email_code') || pm.collectionVariables.get('email_code') || '';
const requestJson = JSON.stringify(pm.request.toJSON());
const usesTotp = requestJson.indexOf('{{totp}}') !== -1 || (!emailCode && requestJson.indexOf('{{two_factor_code}}') !== -1);
if (secret && usesTotp) {
  const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
  let bits = '';
  for (const c of secret) { const v = alphabet.indexOf(c); if (v >= 0) bits += v.toString(2).padStart(5, '0'); }
  let keyHex = '';
  for (let i = 0; i + 8 <= bits.length; i += 8) keyHex += parseInt(bits.substr(i, 8), 2).toString(16).padStart(2, '0');
  // Codes are single-use: if this 30 s window was already used, take the next one (server window ±1).
  let counter = Math.floor(Date.now() / 1000 / 30);
  const last = parseInt(pm.collectionVariables.get('totp_last_counter') || '0', 10);
  if (counter <= last) {
    if (last + 1 > counter + 1) console.warn('TOTP for this window was already used: wait 30 seconds and send again.');
    counter = Math.min(last + 1, counter + 1);
  }
  const hmac = CryptoJS.HmacSHA1(CryptoJS.enc.Hex.parse(counter.toString(16).padStart(16, '0')), CryptoJS.enc.Hex.parse(keyHex)).toString(CryptoJS.enc.Hex);
  const offset = parseInt(hmac.slice(-1), 16);
  const code = ((parseInt(hmac.substr(offset * 2, 8), 16) & 0x7fffffff) % 1000000).toString().padStart(6, '0');
  pm.variables.set('totp', code);
  pm.collectionVariables.set('totp_last_counter', String(counter));
}
// E-mail 2FA (TWO_FACTOR_METHOD=email): paste the e-mailed code into email_code.
pm.variables.set('two_factor_code', emailCode || pm.variables.get('totp') || '');
""".strip().split('\n')

DESCRIPTION = """Paschim Today API v1 — generated from `docs/openapi.json` by `docs/postman/build_collection.py`.

**Quick start**
1. Import this collection and `PaschimToday.local.postman_environment.json`, select the environment.
2. Set `login` / `password` (e.g. the super-admin from your `.env`). If the account already has 2FA, paste its base32 secret into `totp_secret` — codes are generated automatically.
3. Run **Auth → Login**, then **Auth → 2FA challenge** when the response says `two_factor_required`.
   `two_factor_method: email` (TWO_FACTOR_METHOD=email): copy the e-mailed code (locally: storage/logs, MAIL_MAILER=log) into `email_code` first.
   Authenticator accounts: **Me → Enable 2FA** (saves `totp_secret`) → **Me → Confirm 2FA**.
4. Run **CMS · Taxonomy → List categories** once (saves `category_uid`), then **CMS · Stories → Create story**.

Dangerous permissions (e.g. role/permission changes, publish) need a 2FA confirmation in the last 15 minutes: run **Me → Confirm 2FA** again before them.

File uploads (multipart) point at `docs/postman/fixtures/…`. In Postman set *Settings → General → Working directory* to the repository root (or reselect the file in the body tab).

Responses: `{data, meta, links}`; errors: `{error: {code, message, details, request_id}}`."""

collection = {
    'info': {
        '_postman_id': str(uuid.uuid5(uuid.NAMESPACE_URL, 'paschimtoday-api-v1')),
        'name': 'Paschim Today API v1',
        'description': DESCRIPTION,
        'schema': 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json',
    },
    'auth': {'type': 'bearer', 'bearer': [{'key': 'token', 'value': '{{access_token}}', 'type': 'string'}]},
    'event': [{'listen': 'prerequest', 'script': {'type': 'text/javascript', 'exec': PRE_REQUEST}}],
    'item': items,
}

VARIABLES = [
    ('base_url', spec.get('servers', [{}])[0].get('url', 'http://localhost:8000/api')), ('locale', 'ne'),
    ('login', 'superadmin'), ('password', ''), ('email_code', ''), ('new_password', ''), ('totp_secret', ''), ('access_token', ''), ('refresh_token', ''),
    ('challenge_token', ''), ('device_id', ''), ('reader_phone', '9800000001'), ('otp_code', ''), ('password_reset_token', ''),
    ('invitation_token', ''), ('story_uid', ''), ('story_slug', ''), ('revision_number', '1'), ('category_uid', ''), ('category_term_uid', ''),
    ('tag_uid', ''), ('tag_merge_target_uid', ''), ('topic_uid', ''), ('entity_uid', ''), ('user_uid', ''), ('editor_uid', ''), ('role_name', 'editor'),
    ('permission_name', 'media.delete'), ('desk_uid', ''), ('module_key', 'comments'), ('application_uid', ''), ('device_uid', ''),
    ('notification_id', ''), ('upload_uid', ''), ('asset_uid', ''), ('folder_uid', ''), ('template_uid', ''), ('template_version', '1'),
    ('setting_uid', ''), ('setting_version', '1'), ('setting_base_version', '0'), ('category_order', '[]'), ('shift_uid', ''), ('preview_url', ''), ('original_url', ''),
    ('analytics_export_uid', ''), ('analytics_alert_uid', ''), ('accuracy_flag_uid', ''), ('scorecard_appeal_uid', ''),
    ('analytics_location_type', 'district'), ('analytics_location_slug', 'kailali'), ('analytics_rule_key', 'viral_story'),
]
collection['variable'] = [{'key': k, 'value': v} for k, v in VARIABLES if k not in ('password', 'new_password', 'totp_secret')] + [
    {'key': 'totp_last_counter', 'value': '0'}]

env = {
    'id': str(uuid.uuid5(uuid.NAMESPACE_URL, 'paschimtoday-env-local')),
    'name': 'Paschim Today · local',
    'values': [{'key': k, 'value': v, 'type': 'secret' if k in ('password', 'new_password', 'totp_secret', 'access_token', 'refresh_token') else 'default', 'enabled': True}
               for k, v in VARIABLES if k in ('base_url', 'locale', 'login', 'password', 'email_code', 'new_password', 'totp_secret', 'reader_phone', 'access_token', 'refresh_token')],
    '_postman_variable_scope': 'environment',
}

with open(os.path.join(HERE, 'PaschimToday.postman_collection.json'), 'w', encoding='utf-8') as f:
    json.dump(collection, f, ensure_ascii=False, indent=2)
if not COLLECTION_ONLY:
    with open(os.path.join(HERE, 'PaschimToday.local.postman_environment.json'), 'w', encoding='utf-8') as f:
        json.dump(env, f, ensure_ascii=False, indent=2)

count = sum(len(f['item']) for f in items)
print(f'{count} requests in {len(items)} folders')
