import requests
from bs4 import BeautifulSoup
from datetime import datetime

def check_backlink(page_url: str, target: str):
    """Check if target domain exists in page_url and return details."""
    result = {
        "url": page_url,
        "status": "Not Found ❌",
        "http_code": None,
        "anchor_text": None,
        "around_text": None,
        "rel": None,
        "last_seen": datetime.now().isoformat()
    }

    try:
        response = requests.get(page_url, timeout=10, headers={"User-Agent": "Mozilla/5.0"})
        result["http_code"] = response.status_code

        if response.status_code == 200:
            soup = BeautifulSoup(response.text, "html.parser")
            for a in soup.find_all("a", href=True):
                if target in a["href"]:
                    result["status"] = "Found ✅"
                    result["anchor_text"] = a.get_text(strip=True)
                    parent_text = a.find_parent().get_text(" ", strip=True)
                    result["around_text"] = parent_text[:200]
                    result["rel"] = a.get("rel")
                    break
    except Exception as e:
        result["status"] = f"Error ❌ ({str(e)})"

    return result
