# -*- coding: utf-8 -*-
"""백제약품 주문 원장 페이지 분석"""

import asyncio
import json
import os
from dotenv import load_dotenv

load_dotenv()

async def analyze_order_ledger():
    from playwright.async_api import async_playwright
    
    username = os.getenv('BAEKJE_USER_ID')
    password = os.getenv('BAEKJE_PASSWORD')
    
    print(f'Username: {username}')
    
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=False)
        context = await browser.new_context()
        page = await context.new_page()
        
        # 로그인 페이지
        await page.goto('https://ibjp.co.kr/dist/login', timeout=15000)
        await page.wait_for_load_state('networkidle', timeout=10000)
        
        # 로그인 폼 입력
        inputs = await page.locator('input[type="text"], input[type="password"]').all()
        if len(inputs) >= 2:
            await inputs[0].fill(username)
            await inputs[1].fill(password)
        
        # 로그인 버튼 클릭
        buttons = await page.locator('button').all()
        for btn in buttons:
            text = await btn.text_content()
            if '로그인' in (text or ''):
                await btn.click()
                break
        
        # 로그인 완료 대기
        try:
            await page.wait_for_url('**/comOrd**', timeout=15000)
            print('Login successful, redirected to comOrd')
        except Exception as e:
            print(f'URL wait failed: {e}')
            await asyncio.sleep(3)
        
        print(f'Current URL: {page.url}')
        
        # 주문 원장 페이지로 이동
        await page.goto('https://ibjp.co.kr/dist/ordLedger', timeout=15000)
        await page.wait_for_load_state('networkidle', timeout=15000)
        
        print(f'Order Ledger URL: {page.url}')
        
        # 페이지 HTML 저장
        html = await page.content()
        with open('ordLedger_page.html', 'w', encoding='utf-8') as f:
            f.write(html)
        print('Page HTML saved to ordLedger_page.html')
        
        # 스크린샷 저장
        await page.screenshot(path='ordLedger_screenshot.png', full_page=True)
        print('Screenshot saved')
        
        # 테이블 데이터 분석
        tables = await page.locator('table').all()
        print(f'Found {len(tables)} tables')
        
        for i, table in enumerate(tables):
            headers = await table.locator('th').all()
            header_texts = [await h.text_content() for h in headers]
            print(f'Table {i} headers: {header_texts}')
        
        # 페이지 텍스트 출력 (분석용)
        body_text = await page.locator('body').text_content()
        print('\n=== Page Text Preview ===')
        print(body_text[:3000] if body_text else 'No text')
        
        await asyncio.sleep(30)  # 페이지 확인 시간
        await browser.close()

if __name__ == '__main__':
    asyncio.run(analyze_order_ledger())
