import sys, os, base64, zipfile, io, re, json, asyncio
sys.path.insert(0, 'backend')
import httpx
import paramiko

def _fill_empty_tag(text, tag, value):
    text = re.sub(r'<' + re.escape(tag) + r'\s*/>', f'<{tag}>{value}</{tag}>', text)
    text = re.sub(r'<' + re.escape(tag) + r'\s*>\s*</' + re.escape(tag) + r'>', f'<{tag}>{value}</{tag}>', text)
    return text

def modify_skeleton(file_data_b64, org_id, apply_type):
    raw = base64.b64decode(file_data_b64)
    buf_out = io.BytesIO()
    with zipfile.ZipFile(io.BytesIO(raw), 'r') as zin:
        with zipfile.ZipFile(buf_out, 'w', zipfile.ZIP_DEFLATED) as zout:
            for item in zin.infolist():
                data = zin.read(item.filename)
                name_lower = item.filename.lower()
                if name_lower.endswith('/kousei.xml') or name_lower == 'kousei.xml':
                    text = data.decode('utf-8', errors='replace')
                    fills = [
                        ('受付行政機関ID', org_id),
                        ('手続ID',         '900A013800001000'),
                        ('手続名称',       'ＡＰＩテスト用手続（電子送達関係手続）（通）０００１'),
                        ('申請種別',       apply_type),
                        ('氏名フリガナ',   'テスト　タロウ'),
                        ('氏名',           'テスト　タロウ'),
                        ('郵便番号',       '1300022'),
                        ('住所',           '東京都墨田区江東橋４丁目３１番１０号'),
                    ]
                    for tag, value in fills:
                        text = _fill_empty_tag(text, tag, value)
                    data = text.encode('utf-8')
                zout.writestr(item, data)
    return base64.b64encode(buf_out.getvalue()).decode()


async def test(org_id, access_token, file_data_b64):
    modified = modify_skeleton(file_data_b64, org_id, '新規申請')
    async with httpx.AsyncClient() as client:
        r = await client.post(
            'https://api2.sbx.e-gov.go.jp/shinsei/v2/post-apply',
            headers={
                'Authorization': f'Bearer {access_token}',
                'Content-Type': 'application/json',
            },
            json={
                'proc_id': '900A013800001000',
                'send_file': {
                    'file_name': '900A013800001000.zip',
                    'file_data': modified,
                },
            },
            timeout=120,
        )
        print(f'org_id={org_id}: HTTP {r.status_code}')
        try:
            body = r.json()
            if r.is_success:
                print('SUCCESS:', json.dumps(body, ensure_ascii=False))
            else:
                report = body.get('report_list', [])
                for rep in report:
                    print('  ERROR:', rep.get('content', ''))
                if not report:
                    print('  BODY:', json.dumps(body, ensure_ascii=False)[:300])
        except Exception:
            print('BODY:', r.text[:500])
    return r.status_code


async def main():
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect('192.168.0.61', username='root', password='59911784')
    stdin, stdout, stderr = ssh.exec_command('cat /volume1/docker/njts-accounting/backend/egov_data/tokens.json')
    tokens = json.loads(stdout.read())
    access_token = tokens['access_token']
    ssh.close()

    # スケルトン取得
    resp = httpx.get(
        'https://api2.sbx.e-gov.go.jp/shinsei/v2/procedure/900A013800001000',
        headers={'Authorization': f'Bearer {access_token}'},
        timeout=30
    )
    file_data_b64 = resp.json()['results']['file_data']

    for org_id in ['100001', '100138', '100900', '100000', '100013']:
        sc = await test(org_id, access_token, file_data_b64)
        if sc == 200:
            break

asyncio.run(main())
