# Minimum Viable Flow (Python) - contract-only example
# Requires requests. Set env vars: API_BASE, EMAIL, PASSCODE, ORGCODE, INVITE_CODE.

import os
import requests

API_BASE = os.getenv('API_BASE', 'https://api.g3nretailstack.com')
EMAIL = os.getenv('EMAIL', 'user@example.com')
PASSCODE = os.getenv('PASSCODE', 'Passw0rd!123')
ORGCODE = os.getenv('ORGCODE', 'ACME')
INVITE_CODE = os.getenv('INVITE_CODE', 'INV123')

session = requests.Session()


def post(path, body, headers=None):
    url = f"{API_BASE}{path}"
    res = session.post(url, json=body, headers=headers)
    data = res.json()
    if not data.get('success'):
        raise RuntimeError(f"{path} failed: {data.get('error')}")
    return data.get('data')


def get(path, params, headers=None):
    url = f"{API_BASE}{path}"
    res = session.get(url, params=params, headers=headers)
    data = res.json()
    if not data.get('success'):
        raise RuntimeError(f"{path} failed: {data.get('error')}")
    return data.get('data')


session_data = post('/usm/session/create', {
    'email': EMAIL,
    'passcode': PASSCODE,
    'caption': 'sdk',
    'session_label': 'sdk',
    'reason': 'login',
})

session_guid = session_data['session_guid']
user_guid = session_data['user_id']

ofm_headers = { 'x-session-guid': session_guid }
org = post('/ofm/org/create', {
    'orgcode': ORGCODE,
    'invitation_code': INVITE_CODE,
    'user_guid': user_guid,
    'caption': 'Acme HQ',
}, ofm_headers)

org_guid = org['org_guid']
org_rev = org.get('revision')
print(f"Operator-only: verify org via direct Lambda: org_guid={org_guid}, expected_revision={org_rev}")

physical = post('/ofm/facility/physical/create', {
    'org_guid': org_guid,
    'code': 'PHYS1',
    'caption': 'HQ',
    'address': { 'street': '1 Main St', 'city': 'Austin', 'region': 'TX', 'country': 'US' },
    'phone': '+1-555-0100',
}, ofm_headers)

legal = post('/ofm/facility/legal/create', {
    'org_guid': org_guid,
    'code': 'LEG1',
    'caption': 'Acme LLC',
    'address': { 'street': '1 Main St', 'city': 'Austin', 'region': 'TX', 'country': 'US' },
}, ofm_headers)

logical = post('/ofm/facility/logical/create', {
    'org_guid': org_guid,
    'code': 'LOG1',
    'caption': 'Online DC',
    'physical_guid': physical['physical_guid'],
    'legal_guid': legal['legal_guid'],
}, ofm_headers)

channel = post('/ofm/sales-channel/create', {
    'org_guid': org_guid,
    'logical_guid': logical['logical_guid'],
    'channel_code': 'WEB',
    'market_code': 'US',
    'locale_codes': ['en-US'],
    'default_locale_code': 'en-US',
}, ofm_headers)

post('/ofm/sales-channel/status', {
    'org_guid': org_guid,
    'channel_guid': channel['channel_guid'],
    'status': 'active',
    'expected_revision': channel['revision'],
    'reason': 'go-live',
}, ofm_headers)

pvm_headers = { 'x-orgcode': ORGCODE, 'x-session-guid': session_guid }

division = post('/pvm/division', { 'code': 'DIV1', 'caption': 'Division 1' }, pvm_headers)
post('/pvm/division/status', {
    'division_id': division['division_id'],
    'status': 'active',
    'expected_revision': division['revision'],
}, pvm_headers)

department = post('/pvm/department', {
    'division_id': division['division_id'],
    'code': 'DEPT1',
    'caption': 'Department 1',
}, pvm_headers)
post('/pvm/department/status', {
    'department_id': department['department_id'],
    'status': 'active',
    'expected_revision': department['revision'],
}, pvm_headers)

category = post('/pvm/category', {
    'department_id': department['department_id'],
    'code': 'CAT1',
    'caption': 'Category 1',
}, pvm_headers)
post('/pvm/category/status', {
    'category_id': category['category_id'],
    'status': 'active',
    'expected_revision': category['revision'],
}, pvm_headers)

vendor = post('/pvm/vendor', { 'code': 'VEND1', 'caption': 'Vendor 1' }, pvm_headers)
post('/pvm/vendor/status', {
    'vendor_id': vendor['vendor_id'],
    'status': 'verified',
    'expected_revision': vendor['revision'],
}, pvm_headers)

manufacturer = post('/pvm/manufacturer', { 'code': 'MFG1', 'caption': 'Manufacturer 1' }, pvm_headers)
post('/pvm/manufacturer/status', {
    'manufacturer_id': manufacturer['manufacturer_id'],
    'status': 'verified',
    'expected_revision': manufacturer['revision'],
}, pvm_headers)

style = post('/pvm/style', {
    'code': 'STYLE1',
    'category_id': category['category_id'],
    'vendor_ids': [vendor['vendor_id']],
    'manufacturer_ids': [manufacturer['manufacturer_id']],
    'vendor_primary': vendor['vendor_id'],
    'manufacturer_primary': manufacturer['manufacturer_id'],
}, pvm_headers)
post('/pvm/style/status', {
    'style_id': style['style_id'],
    'status': 'active',
    'expected_revision': style['revision'],
}, pvm_headers)

variant = post('/pvm/variant', {
    'style_id': style['style_id'],
    'selections': [],
    'code': 'VAR1',
}, pvm_headers)
post('/pvm/variant/status', {
    'style_id': style['style_id'],
    'variant_id': variant['variant_id'],
    'status': 'active',
    'expected_revision': variant['revision'],
}, pvm_headers)

post('/pvm/identifier/add', {
    'style_id': style['style_id'],
    'variant_id': variant['variant_id'],
    'type': 'sku',
    'value': 'SKU-001',
}, pvm_headers)

pmc_headers = { 'x-orgcode': ORGCODE, 'x-session-guid': session_guid }
run = post('/pmc/publish/run/start', {
    'style_id': style['style_id'],
    'variant_id': variant['variant_id'],
    'channel_guid': channel['channel_guid'],
    'reason': 'initial publish',
}, pmc_headers)

run_rev = run.get('revision')
for _ in range(10):
    step = post('/pmc/publish/run/step', { 'run_id': run['run_id'], 'expected_revision': run_rev }, pmc_headers)
    if step.get('revision'):
        run_rev = step['revision']
    if step.get('status') and step['status'] != 'running':
        break

product = get('/pmc/product/get', {
    'variant_id': variant['variant_id'],
    'channel_guid': channel['channel_guid'],
}, pmc_headers)

print('Published product:', product.get('product', {}).get('product_id'))
