#!/usr/bin/env python3
# 기존 발송 코드(plugin/mail.php, plugin/alimTalk.php)에 소스로 박혀 있는 계정 값을
# common/setting.php 의 상수로 옮긴다. (계정 값을 문서·테스트에 쓰지 않으려는 목적)
# - 값은 출력하지 않고 상수 이름만 출력한다
# - 이미 정의돼 있으면 건너뛴다
# - PY_RUNNER(python 실행기 경로, 테스트에서 교체 가능)도 함께 추가한다
import re, sys, os

root = sys.argv[1] if len(sys.argv) > 1 else '.'

def read(rel):
    # newline='' : 줄바꿈(CRLF)을 변환하지 않고 그대로 읽는다
    return open(os.path.join(root, rel), encoding='utf-8', newline='').read()

mail = read('plugin/mail.php')
ali = read('plugin/alimTalk.php')
setting_path = os.path.join(root, 'common/setting.php')
setting = read('common/setting.php')

def one(pattern, src, name):
    found = set(re.findall(pattern, src))
    assert len(found) == 1, '%s 값을 하나로 특정하지 못함 (%d개)' % (name, len(found))
    return found.pop()

consts = [
    ('DIRECTSEND_USERNAME', one(r'\$username\s*=\s*"([^"]+)"', mail, 'DIRECTSEND_USERNAME')),
    ('DIRECTSEND_KEY',      one(r'\$key\s*=\s*"([^"]+)"', mail, 'DIRECTSEND_KEY')),
    ('ALIGO_USERID',        one(r"'userid'\s*=>\s*'([^']+)'", ali, 'ALIGO_USERID')),
    ('ALIGO_SENDERKEY',     one(r"'senderkey'\s*=>\s*'([^']+)'", ali, 'ALIGO_SENDERKEY')),
    ('ALIGO_SENDER',        one(r"'sender'\s*=>\s*'([^']+)'", ali, 'ALIGO_SENDER')),
]

nl = '\r\n' if '\r\n' in setting else '\n'
lines = []
for name, value in consts:
    if "define('%s'" % name in setting:
        print('건너뜀(이미 있음):', name)
        continue
    escaped = value.replace('\\', '\\\\').replace("'", "\\'")
    lines.append("    define('%s', '%s');%s" % (name, escaped, nl))
    print('추가:', name)

if "define('PY_RUNNER'" not in setting:
    lines.append("    // python 실행기 (테스트에서는 가짜 실행기를 먼저 define 해서 교체한다)" + nl)
    lines.append("    if (!defined('PY_RUNNER')) { define('PY_RUNNER', BASE_PATH . 'python/run_python.sh'); }" + nl)
    print('추가: PY_RUNNER')

if lines:
    anchor = re.search(r"^[ \t]*define\('LAXTHA_BASEPATH'[^\n]*\n", setting, re.M)
    assert anchor, 'LAXTHA_BASEPATH 위치를 찾지 못함'
    header = ("    // ----- 새 리포트 발송 흐름(basic)용 상수 (기존 plugin/mail.php, plugin/alimTalk.php 에 있던 값을 분리) -----" + nl)
    setting = setting[:anchor.end()] + nl + header + ''.join(lines) + setting[anchor.end():]
    open(setting_path, 'w', encoding='utf-8', newline='').write(setting)
