#!/usr/bin/env python3
"""GUARDiA Messenger Gitea 저장소 생성 + Push"""
import paramiko, time, sys, os, io, zipfile

HOST      = '101.79.17.164'
USER      = 'root'
PASS      = '1q2w3e!Q'
LOCAL_APP = 'C:/GUARDiA/app'
SEP       = chr(92)

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(HOST, username=USER, password=PASS, timeout=15)
sftp = client.open_sftp()

def run(label, cmd, timeout=60):
    print(f'\n[{label}]')
    chan = client.get_transport().open_session()
    chan.set_combine_stderr(True)
    chan.exec_command(cmd)
    start = time.time()
    while not chan.exit_status_ready():
        if chan.recv_ready(): sys.stdout.buffer.write(chan.recv(4096)); sys.stdout.flush()
        if time.time()-start > timeout: print('[TIMEOUT]'); break
        time.sleep(0.3)
    while chan.recv_ready(): sys.stdout.buffer.write(chan.recv(4096))
    sys.stdout.flush()
    chan.recv_exit_status()

# --- 1. 저장소 생성 ---
create_py = """
import urllib.request, json, base64, urllib.error
G = 'http://localhost:3000'
h = {'Content-Type':'application/json','Authorization':'Basic '+base64.b64encode(b'zio:Zio@Admin2026!').decode()}
d = json.dumps({'name':'guardia-messenger','description':'GUARDiA Messenger Mobile App','private':False,'auto_init':False}).encode()
req = urllib.request.Request(G+'/api/v1/user/repos',data=d,method='POST',headers=h)
try:
    r=urllib.request.urlopen(req)
    print('OK:',json.loads(r.read()).get('full_name'))
except urllib.error.HTTPError as e:
    b=e.read(); print('HTTP',e.code,b.decode()[:100])
"""
with sftp.open('/tmp/cr.py','w') as f: f.write(create_py)
run('저장소 생성', 'python3 /tmp/cr.py')

# --- 2. 소스 패키징 ---
print('\n[소스 패키징]')
SKIP = {'node_modules','.git','android','ios','__pycache__','.expo'}
buf = io.BytesIO(); n = 0
with zipfile.ZipFile(buf,'w',zipfile.ZIP_DEFLATED) as zf:
    for root,dirs,files in os.walk(LOCAL_APP):
        dirs[:] = [d for d in dirs if d not in SKIP]
        rel = os.path.relpath(root,LOCAL_APP).replace(SEP,'/')
        for f in files:
            if f.endswith(('.pyc','.log')): continue
            arc = f if rel=='.' else f'{rel}/{f}'
            zf.write(os.path.join(root,f),arc); n+=1
buf.seek(0)
with sftp.open('/tmp/msg.zip','wb') as f: f.write(buf.read())
print(f'  {n}개 파일')

# --- 3. git push (서버 스크립트) ---
push_py = """
import subprocess, os

os.makedirs('/tmp/msg-push', exist_ok=True)
subprocess.run(['rm','-rf','/tmp/msg-push'], check=False)
os.makedirs('/tmp/msg-push')
subprocess.run(['unzip','-q','/tmp/msg.zip','-d','/tmp/msg-push'], check=True)

env = {'HOME':'/root','PATH':'/usr/bin:/bin'}
cwd = '/tmp/msg-push'

for cmd in [
    ['git','init','-q'],
    ['git','config','user.email','ci@zioinfo.co.kr'],
    ['git','config','user.name','ZioCI'],
    ['git','add','-A'],
    ['git','commit','-q','-m','feat: GUARDiA Messenger v1.0.0 initial commit'],
    ['git','remote','add','origin','http://zio:Zio%40Admin2026%21@localhost:3000/zio/guardia-messenger.git'],
    ['git','push','origin','main'],
]:
    r = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True)
    if r.returncode != 0 and cmd[1] not in ['config','remote']:
        print('ERR',cmd[1],r.stderr[:100])
    else:
        print('OK',cmd[1])
"""
with sftp.open('/tmp/push.py','w') as f: f.write(push_py)
run('Git Push', 'python3 /tmp/push.py', 60)

# --- 4. Webhook ---
wh_py = """
import urllib.request, json, base64
G='http://localhost:3000'
h={'Content-Type':'application/json','Authorization':'Basic '+base64.b64encode(b'zio:Zio@Admin2026!').decode()}
d=json.dumps({'type':'gitea','active':True,'config':{'url':'http://localhost:9999/','content_type':'json','secret':'zioinfo-deploy-2026'},'events':['push']}).encode()
req=urllib.request.Request(G+'/api/v1/repos/zio/guardia-messenger/hooks',data=d,method='POST',headers=h)
try:
    r=urllib.request.urlopen(req); print('Webhook OK, ID:',json.loads(r.read()).get('id'))
except Exception as e: print('Webhook 오류:',e)
"""
with sftp.open('/tmp/wh.py','w') as f: f.write(wh_py)
run('Webhook 등록', 'python3 /tmp/wh.py')

# --- 5. 최종 확인 ---
check_py = """
import urllib.request, json, base64
G='http://localhost:3000'
h={'Authorization':'Basic '+base64.b64encode(b'zio:Zio@Admin2026!').decode()}
r=urllib.request.Request(G+'/api/v1/repos/zio/guardia-messenger',headers=h)
try:
    d=json.loads(urllib.request.urlopen(r).read())
    print('저장소:', d.get('full_name'))
    print('URL:   ', d.get('html_url'))
    print('브랜치:', d.get('default_branch'))
except Exception as e: print('오류:',e)

# 브랜치 목록
r2=urllib.request.Request(G+'/api/v1/repos/zio/guardia-messenger/branches',headers=h)
try:
    branches=json.loads(urllib.request.urlopen(r2).read())
    print('브랜치 목록:', [b['name'] for b in branches])
except: pass
"""
with sftp.open('/tmp/check.py','w') as f: f.write(check_py)
sftp.close()
run('최종 확인', 'python3 /tmp/check.py')

client.close()
