import logging
import requests
from datetime import datetime
import time

# ロガーの設定
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def notify_scraping_status(site_id: int, status: str, started_at: datetime, finished_at: datetime = None, log: str = None) -> None:
    """スクレイピングの状態をAPIに通知する"""
    try:
        url = "http://153.125.147.12/api/scraping-results"
        headers = {
            "Content-Type": "application/json",
            "X-Scraping-Api-Key": "eaa1c9c7c0b498fca81b9e7c78074d2e"
        }
        data = {
            "site_id": site_id,
            "status": status,
            "started_at": started_at.isoformat(),
            "triggered_by": "manual"
        }
        
        if finished_at:
            data["finished_at"] = finished_at.isoformat()
        if log:
            data["log"] = log
            
        response = requests.post(url, headers=headers, json=data)
        response.raise_for_status()
        
        try:
            response_data = response.json()
            logger.info(f"Successfully notified scraping status: {status}")
            logger.info(f"Response: {response_data}")
        except ValueError as e:
            logger.warning(f"Response is not JSON: {response.text}")
            logger.info(f"Successfully notified scraping status: {status}")
            
    except requests.exceptions.RequestException as e:
        logger.error(f"Failed to notify scraping status: {e}")
        raise

def test_scraping_status_api():
    """スクレイピング状態のAPIをテストする"""
    try:
        # テスト開始
        logger.info("Starting API test...")
        
        # 1. スクレイピング開始の通知
        started_at = datetime.now()
        logger.info("Testing 'running' status...")
        notify_scraping_status(1, "running", started_at)
        
        # 少し待機
        time.sleep(2)
        
        # 2. スクレイピング成功の通知
        finished_at = datetime.now()
        logger.info("Testing 'success' status...")
        notify_scraping_status(
            1, 
            "success", 
            started_at, 
            finished_at, 
            "テスト用のスクレイピングが正常に完了しました"
        )
        
        # 少し待機
        time.sleep(2)
        
        # 3. スクレイピング失敗の通知
        started_at = datetime.now()
        finished_at = datetime.now()
        logger.info("Testing 'failure' status...")
        notify_scraping_status(
            1, 
            "failure", 
            started_at, 
            finished_at, 
            "テスト用のエラー: タイムアウト"
        )
        
        logger.info("API test completed successfully")
        
    except Exception as e:
        logger.error(f"API test failed: {e}")
        raise

if __name__ == '__main__':
    test_scraping_status_api() 