import re, json, httpx, paramiko, base64, zipfile, io, asyncio

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']

candidates = [
    'ＡＰＩテスト用手続（電子送達関係手続）（通）０００１',
    'ＡＰＩテスト用手続（電子送達関係手続）（通）０００１＿０１',
    '電子送付開始手続き',
    '【オンライン事業所年金情報サービス】電子送付開始手続き',
    'ＡＰＩテスト用手続（電子送達関係手続）',
    'ＡＰＩテスト用手続（電子送達関係手続）（通）',
    'オンライン事業所年金情報サービス　電子送付開始手続き',
    'ＡＰＩテスト用手続（電子送達関係手続）（通）０００１　電子送付開始手続き',
]

def fill_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 build_zip(file_data_b64, proc_name):
    raw = base64.b64decode(file_data_b64)
    buf = io.BytesIO()
    with zipfile.ZipFile(io.BytesIO(raw)) as zin:
        with zipfile.ZipFile(buf, 'w', zipfile.ZIP_DEFLATED) as zout:
            for item in zin.infolist():
                data = zin.read(item.filename)
                if 'kousei' in item.filename.lower():
                    text = data.decode('utf-8', 'replace')
                    for tag, val in [
                        ('受付行政機関ID', '100001'),
                        ('手続ID', '900A013800001000'),
                        ('手続名称', proc_name),
                        ('申請種別', '新規申請'),
                        ('氏名フリガナ', 'テスト　タロウ'),
                        ('氏名', 'テスト　タロウ'),
                        ('郵便番号', '1300022'),
                        ('住所', '東京都墨田区江東橋４丁目３１番１０号'),
                    ]:
                        text = fill_tag(text, tag, val)
                    data = text.encode('utf-8')
                zout.writestr(item, data)
    return base64.b64encode(buf.getvalue()).decode()


async def try_name(proc_name):
    modified = build_zip(file_data_b64, proc_name)
    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=60,
        )
        name_short = repr(proc_name[:35])
        print(f'name={name_short}: HTTP {r.status_code}')
        if r.is_success:
            print('  SUCCESS:', json.dumps(r.json(), ensure_ascii=False)[:200])
        else:
            body = r.json()
            errs = [rep.get('content', '') for rep in body.get('report_list', [])]
            if errs:
                for e in errs:
                    print(f'  ERR: {e}')
            else:
                print(f'  BODY: {json.dumps(body, ensure_ascii=False)[:200]}')
        return r.status_code


async def main():
    for name in candidates:
        sc = await try_name(name)
        if sc == 200:
            break

asyncio.run(main())
