"""Grok API adapter extracted unchanged from the landlord Grok fork. See SOURCE.json."""
import os, re
from pathlib import Path
from typing import List
import requests as req_lib

def extract_phones(text: str) -> List[str]:
    """Return deduplicated phone strings found in text, order preserved."""
    seen = set()
    result = []
    for m in PHONE_RE.findall(text):
        normalized = re.sub(r'[\s.\-()]', '', m)
        if normalized not in seen:
            seen.add(normalized)
            result.append(m)
    return result

PHONE_RE = re.compile(r'\b(\(?[2-9]\d{2}\)?[\s.\-]?\d{3}[\s.\-]?\d{4})\b')

API_URL      = "https://api.x.ai/v1/responses"

MODEL        = os.environ.get("XAI_MODEL", "grok-4.7")

def api_key():
    """Keep credentials server-side; optionally read an existing key file."""
    key = os.environ.get("XAI_API_KEY", "").strip()
    if not key and os.environ.get("XAI_API_KEY_FILE"):
        key = Path(os.environ["XAI_API_KEY_FILE"]).read_text().strip()
    return key

CONF_RE = re.compile(
    r"confidence[:\s]+([0-9]\.[0-9]+)|conf[:\s]+([0-9]\.[0-9]+)|([0-9]\.[0-9]+)\s*/\s*1\.0",
    re.IGNORECASE,
)

URL_RE = re.compile(r"https?://[^\s\)\]\[\"\'<>]+")

def parse_confidence(text: str) -> float:
    m = CONF_RE.search(text)
    if m:
        val = next(v for v in m.groups() if v is not None)
        return round(float(val), 2)
    return 0.6

def parse_source_url(text: str) -> str | None:
    skip = ("startpage", "duckduck", "google.com/search", "bing.com/search", "x.ai")
    for u in URL_RE.findall(text):
        u = u.rstrip(".,;)")
        if not any(s in u for s in skip):
            return u
    return None

def call_grok(api_key: str, prompt: str) -> dict:
    try:
        r = req_lib.post(
            API_URL,
            headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
            json={"model": MODEL, "input": prompt, "tools": [{"type": "web_search"}],
                  "max_tool_calls": 3, "max_output_tokens": 1800, "store": False},
            timeout=120,
        )
        r.raise_for_status()
        data = r.json()
        if data.get("error") or data.get("status") == "incomplete":
            raise ValueError("Grok did not complete its research response")

        text = ""
        citations = []
        for item in data.get("output", []):
            if item.get("type") == "message":
                for c in item.get("content", []):
                    if c.get("type") == "output_text":
                        text += c.get("text", "")
                        citations.extend(a.get("url", "") for a in c.get("annotations", [])
                                         if a.get("type") == "url_citation")

        if not text.strip():
            raise ValueError("Grok returned no research text")
        phones = extract_phones(text)
        return {
            "text": text,
            "phones": phones,
            "confidence": parse_confidence(text) if phones else 0.0,
            "source_url": parse_source_url(text) or next((u for u in citations if u.startswith("https://")), None),
            "error": None,
        }
    except Exception as exc:
        return {"text": "", "phones": [], "confidence": 0.0, "source_url": None, "error": str(exc)}
