#!/usr/bin/env python3
"""
AmazonRank Environment & Anti-Bot Diagnostic Worker
SoftnCode - amazonrank.softncode.com
"""

import urllib.request
import urllib.error
import re
import sqlite3
import datetime
import os

# 1. Target a known, evergreen ASIN (e.g., standard Amazon product)
TEST_ASIN = "B07WZLG91P"
TARGET_URL = f"https://www.amazon.com/dp/{TEST_ASIN}"
DB_FILE = os.path.join(os.path.dirname(__file__), "amazonrank_test.db")

# 2. Emulate realistic browser headers
HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
    "Accept-Language": "en-US,en;q=0.9",
    "Accept-Encoding": "identity",  # Keep uncompressed for raw stream reading
    "Connection": "keep-alive",
    "Upgrade-Insecure-Requests": "1",
}

def init_db():
    conn = sqlite3.connect(DB_FILE)
    cursor = conn.cursor()
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS diagnostic_logs (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            timestamp TEXT,
            asin TEXT,
            http_code INTEGER,
            is_blocked INTEGER,
            title TEXT,
            extracted_bsr TEXT,
            extracted_rating REAL,
            raw_snippet TEXT
        )
    """)
    conn.commit()
    return conn

def run_diagnostic():
    conn = init_db()
    cursor = conn.cursor()
    now = datetime.datetime.utcnow().isoformat()

    req = urllib.request.Request(TARGET_URL, headers=HEADERS)
    http_code = 0
    html_content = ""
    is_blocked = 0
    title = None
    bsr = None
    rating = None

    try:
        with urllib.request.urlopen(req, timeout=15) as response:
            http_code = response.getcode()
            html_content = response.read().decode("utf-8", errors="ignore")
    except urllib.error.HTTPError as e:
        http_code = e.code
        html_content = e.read().decode("utf-8", errors="ignore")
    except Exception as e:
        http_code = 999
        html_content = str(e)

    # 3. Detect Amazon Anti-Bot Signatures
    # Amazon typically responds with HTTP 200 or 503 accompanied by specific block strings
    block_signatures = [
        "api-services-support@amazon.com",
        "Type the characters you see below",
        "To discuss automated access to Amazon data please contact",
        "/errors/validateCaptcha"
    ]
    if any(sig in html_content for sig in block_signatures) or http_code in [503, 403]:
        is_blocked = 1

    # 4. Attempt Data Extraction (Only if not blocked)
    if not is_blocked and http_code == 200:
        # Title extraction
        title_match = re.search(r'<span id="productTitle"[^>]*>\s*([^<]+)\s*</span>', html_content)
        if title_match:
            title = title_match.group(1).strip()

        # Rating extraction
        rating_match = re.search(r'([0-9\.]+) out of 5 stars', html_content)
        if rating_match:
            try:
                rating = float(rating_match.group(1))
            except ValueError:
                pass

        # BSR extraction
        bsr_match = re.search(r'#([0-9,]+)\s+in\s+([A-Za-z\s&]+)\(', html_content)
        if bsr_match:
            bsr = f"#{bsr_match.group(1)} in {bsr_match.group(2).strip()}"

    # 5. Log Results to SQLite
    snippet = html_content[:400].replace("\n", " ").strip()
    cursor.execute("""
        INSERT INTO diagnostic_logs 
        (timestamp, asin, http_code, is_blocked, title, extracted_bsr, extracted_rating, raw_snippet)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    """, (now, TEST_ASIN, http_code, is_blocked, title, bsr, rating, snippet))

    conn.commit()
    conn.close()
    print(f"[{now}] Finished. Code: {http_code} | Blocked: {bool(is_blocked)} | Title: {title}")

if __name__ == "__main__":
    run_diagnostic()