#!/usr/bin/env python3
"""
Ghost Agency Radar - Overpass API (OpenStreetMap) Edition
Trova attività locali (ristoranti, dentisti, idraulici, ecc.) a Parma
che NON hanno sito web. Gratis, legale, non bloccabile.
"""
import os
import csv
import time
import socket
import requests
import json
from pathlib import Path

OVERPASS_URL = "https://overpass.kumi.systems/api/interpreter"
CITY = "Parma"
CITY_BBOX = "44.6,10.1,44.9,10.5"  # bbox approssimativa Parma

# Categorie OSM da cercare (tag -> nome amichevole)
CATEGORIES = {
    "amenity=restaurant": "Ristoranti",
    "amenity=cafe": "Bar/Caffè",
    "amenity=fast_food": "Fast Food",
    "craft=bakery": "Panifici",
    "craft=butcher": "Macellerie",
    "shop=hairdresser": "Parrucchieri",
    "shop=beauty": "Centri Estetici",
    "amenity=dentist": "Dentisti",
    "amenity=pharmacy": "Farmacie",
    "craft=plumber": "Idraulici",
    "craft=electrician": "Elettricisti",
    "shop=car_repair": "Autofficine",
}

HEADERS = {
    "User-Agent": "Mozilla/5.0 (GhostAgency Radar/2.0; +https://svoraj.me)",
    "Accept": "application/json",
}

def check_dns(name, city):
    """Verifica se esiste un dominio probabile per l'attività."""
    clean = "".join(c for c in name if c.isalnum()).lower()
    city_clean = city.lower()
    domains = [
        f"{clean}.it", f"{clean}.com",
        f"{clean}{city_clean}.it", f"{clean}{city_clean}.com",
        f"{clean}-{city_clean}.it", f"{clean}-{city_clean}.com",
    ]
    for domain in domains:
        try:
            socket.gethostbyname(domain)
            return True, domain
        except socket.gaierror:
            continue
    return False, None

def query_overpass(tag):
    """Interroga Overpass API per un tag nella bbox di Parma."""
    query = f"""
    [out:json][timeout:25];
    (
      node[{tag}]({CITY_BBOX});
      way[{tag}]({CITY_BBOX});
      relation[{tag}]({CITY_BBOX});
    );
    out center tags;
    """
    try:
        resp = requests.post(OVERPASS_URL, data={"data": query}, headers=HEADERS, timeout=30)
        resp.raise_for_status()
        return resp.json().get("elements", [])
    except Exception as e:
        print(f"[!] Errore Overpass per {tag}: {e}")
        return []

def extract_info(element):
    """Estrae nome, telefono, indirizzo, website da elemento OSM."""
    tags = element.get("tags", {})
    name = tags.get("name", "").strip()
    if not name:
        return None
    
    phone = tags.get("phone", tags.get("contact:phone", "")).strip()
    website = tags.get("website", tags.get("contact:website", "")).strip()
    
    # Indirizzo
    addr_parts = []
    for k in ["addr:housenumber", "addr:street", "addr:city", "addr:postcode"]:
        v = tags.get(k, "").strip()
        if v:
            addr_parts.append(v)
    address = ", ".join(addr_parts) if addr_parts else "Parma"
    
    # Coordinate
    lat = element.get("lat") or element.get("center", {}).get("lat")
    lon = element.get("lon") or element.get("center", {}).get("lon")
    
    return {
        "nome": name,
        "telefono": phone or "N/A",
        "indirizzo": address,
        "website_osm": website or "N/A",
        "lat": lat,
        "lon": lon,
    }

def run_radar():
    print(f"=================================================================")
    print(f" GHOST AGENCY - RADAR OVERPASS (OpenStreetMap)")
    print(f" Ricerca attività a '{CITY}' senza sito web")
    print(f"=================================================================\n")
    
    all_leads = []
    
    for tag, cat_name in CATEGORIES.items():
        print(f"[*] Scansione {cat_name} ({tag})...")
        elements = query_overpass(tag)
        print(f"    Trovati {len(elements)} elementi OSM")
        
        cat_leads = 0
        for el in elements:
            info = extract_info(el)
            if not info:
                continue
            
            # Se ha già website su OSM, scarta subito
            if info["website_osm"] != "N/A":
                continue
            
            # Controllo DNS bruteforce
            has_dns, domain = check_dns(info["nome"], CITY)
            if has_dns:
                print(f"    [-] {info['nome']}: dominio trovato ({domain})")
                continue
            
            # Lead valido: attività senza website noto
            lead = {
                "Nome": info["nome"],
                "Telefono": info["telefono"],
                "Indirizzo": info["indirizzo"],
                "Categoria": cat_name,
                "Lat": info["lat"],
                "Lon": info["lon"],
            }
            all_leads.append(lead)
            cat_leads += 1
            print(f"    [+] LEAD: {info['nome']} | {info['telefono']} | {info['indirizzo']}")
        
        print(f"    -> {cat_leads} lead per {cat_name}")
        time.sleep(1)  # Rate limiting gentile
    
    # Salvataggio
    if all_leads:
        timestamp = time.strftime("%Y%m%d_%H%M%S")
        filename = f"leads_{CITY.lower()}_{timestamp}_overpass.csv"
        filepath = Path("/home/ubuntu/GhostAgency") / filename
        
        fieldnames = ["Nome", "Telefono", "Indirizzo", "Categoria", "Lat", "Lon"]
        with open(filepath, "w", newline="", encoding="utf-8") as f:
            writer = csv.DictWriter(f, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerows(all_leads)
        
        print(f"\n[+] VITTORIA. Salvati {len(all_leads)} lead in {filename}")
        return filepath
    else:
        print("\n[-] Nessun lead trovato (tutti hanno già sito o dominio)")
        return None

if __name__ == "__main__":
    run_radar()