"""Fixture setup used for the Azure refresh scenario.
Load the Azure test environment first. Run with the downloaded scenario path to
create an inherited Basic process, materialize its inherited Issue type, migrate
the test project, and update the scenario's processId. The scenario itself creates
and deletes its work items and custom Completed state on each comparison side.
After proof, run this script with --cleanup PROCESS_ID to restore Basic and delete
the process. Use only the dedicated test organization and project.
"""
import base64
import json
import os
import re
import sys
import urllib.parse
import urllib.request
from pathlib import Path

ORG = os.environ['AZURE_DEVOPS_TEST_ORG'].rstrip('/')
PROJECT = urllib.parse.quote(os.environ['AZURE_DEVOPS_TEST_PROJECT'])
BASIC = 'b8a3a935-7e91-48b8-a94c-606d37c3e9f2'

def request(path, method='GET', body=None):
    headers = {'Authorization': 'Basic ' + base64.b64encode((':' + os.environ['AZURE_DEVOPS_EXT_PAT']).encode()).decode(), 'Content-Type': 'application/json'}
    req = urllib.request.Request(ORG + path + '?api-version=7.1', method=method, headers=headers, data=json.dumps(body).encode() if body else None)
    with urllib.request.urlopen(req) as response:
        data = response.read()
        return json.loads(data) if data else None

if sys.argv[1] == '--cleanup':
    request(f'/{PROJECT}/_apis/wit/projectprocessmigration', 'POST', {'typeId': BASIC})
    request(f'/_apis/work/processes/{sys.argv[2]}', 'DELETE')
    print('Original Basic process restored; temporary process deleted.')
else:
    process = request('/_apis/work/processes', 'POST', {'name': 'Factory 38986 evidence', 'parentProcessTypeId': BASIC})
    process_id = process['typeId']
    wit = request(f'/_apis/work/processes/{process_id}/workItemTypes', 'POST', {'name': 'Issue', 'inheritsFrom': 'Microsoft.VSTS.WorkItemTypes.Issue', 'color': '339947', 'icon': 'icon_clipboard_issue'})
    request(f'/{PROJECT}/_apis/wit/projectprocessmigration', 'POST', {'typeId': process_id})
    scenario = Path(sys.argv[1])
    content = re.sub(r'const processId = "[^"]+";', f'const processId = "{process_id}";', scenario.read_text())
    content = content.replace('Factory38986evidence.Issue', wit['referenceName'])
    scenario.write_text(content)
    print('Fixture ready. Cleanup process ID: ' + process_id)
