#!/usr/bin/env python3
"""AI 플랫폼 설치 스크립트"""
import paramiko, time, sys

HOST='101.79.17.164'; USER='root'; PASS='1q2w3e!Q'
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=300):
    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.5)
    while chan.recv_ready(): sys.stdout.buffer.write(chan.recv(4096))
    sys.stdout.flush()
    rc = chan.recv_exit_status()
    print(f'exit={rc}'); return rc

install_script = """#!/bin/bash
VENV=/opt/guardia/venv/bin/pip
$VENV install -q --upgrade langchain langchain-community langchain-ollama chromadb sentence-transformers
$VENV install -q langgraph langchain-chroma
echo DONE
"""
with sftp.open('/tmp/install_ai.sh', 'w') as f:
    f.write(install_script)
sftp.close()

run('AI 패키지 설치', 'bash /tmp/install_ai.sh 2>&1 | tail -10', 300)

# 검증 스크립트
verify = """
import sys
results = []
for pkg in ['langchain', 'chromadb', 'langchain_community', 'langchain_ollama', 'langgraph']:
    try:
        m = __import__(pkg)
        ver = getattr(m, '__version__', 'ok')
        results.append('OK  ' + pkg + '==' + str(ver))
    except ImportError as e:
        results.append('FAIL ' + pkg + ': ' + str(e))

for r in results:
    print(r)
ok_cnt = sum(1 for r in results if r.startswith('OK'))
print('\\n결과: ' + str(ok_cnt) + '/' + str(len(results)) + ' PASS')
"""
sftp = client.open_sftp()
with sftp.open('/tmp/verify_ai.py', 'w') as f:
    f.write(verify)
sftp.close()

run('설치 검증', '/opt/guardia/venv/bin/python3 /tmp/verify_ai.py')

# 임베딩 모델 다운로드 확인
run('nomic-embed-text 확인', 'ollama list | grep -i nomic || echo "not yet downloaded"')

# 코드베이스 임베딩 스크립트 생성
embed_script = '''#!/usr/bin/env python3
"""GUARDiA 코드베이스를 ChromaDB에 임베딩"""
import os, sys
os.environ["ANONYMIZED_TELEMETRY"] = "False"

from langchain_community.document_loaders import DirectoryLoader, TextLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_ollama import OllamaEmbeddings
from langchain_chroma import Chroma

APP_DIR = "/opt/guardia/app"
VDB_DIR = "/opt/guardia/vectordb"

print("문서 로딩...")
loader = DirectoryLoader(APP_DIR, glob="**/*.py",
    loader_cls=TextLoader, loader_kwargs={"encoding":"utf-8", "autodetect_encoding":True})
docs = loader.load()
print(f"로드된 파일: {len(docs)}개")

splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=100)
chunks = splitter.split_documents(docs)
print(f"청크 수: {len(chunks)}")

embeddings = OllamaEmbeddings(model="nomic-embed-text", base_url="http://localhost:11434")

print("임베딩 중 (시간 소요)...")
vectordb = Chroma.from_documents(chunks[:50], embeddings,  # 처음 50개만 테스트
    persist_directory=VDB_DIR, collection_name="guardia_codebase")
print(f"임베딩 완료. 저장 위치: {VDB_DIR}")

# 테스트 검색
results = vectordb.similarity_search("라이선스 키 등록", k=2)
print("\\n테스트 검색 결과:")
for r in results:
    print(f"  - {r.metadata.get('source','?')}: {r.page_content[:60]}...")
'''

sftp = client.open_sftp()
with sftp.open('/opt/guardia/app/scripts/embed_codebase.py', 'w') as f:
    f.write(embed_script)
run('embed_codebase.py 생성', 'ls /opt/guardia/app/scripts/')
sftp.close()

client.close()
print('\nAI 플랫폼 설치 완료')
