#!/usr/bin/env python3
"""Websites in, people and emails out, with the ListMiner API.

    export LISTMINER_API_KEY=your_key
    python3 listminer_websites_to_contacts.py websites.csv contacts.csv

websites.csv needs two columns with a header row: website, company_name.
contacts.csv gets one row per person or inbox found.

Uses only Python's standard library. Edit TITLES and SOURCES below to
change who it looks for. API reference: https://listminer.com/docs/api
"""

import csv
import json
import os
import sys
import time
import urllib.error
import urllib.request

BASE = "https://api.prod.cold-email.softwaredoes.com/api/v1"
KEY = os.environ.get("LISTMINER_API_KEY", "")

# Who to look for, and where.
TITLES = ["Owner", "Founder", "CEO"]
SOURCES = ["LINKEDIN", "TEAM_PAGE", "WEBSITE_EMAILS"]

BATCH = 25  # the most websites one call takes
DONE = {"COMPLETED", "COMPLETED_WITH_ERRORS", "FAILED"}
FIELDS = ["website", "company_name", "full_name", "position", "email", "email_type", "linkedin_url", "found_in"]


def call(method, path, body=None, timeout=60):
    req = urllib.request.Request(
        BASE + path,
        method=method,
        data=json.dumps(body).encode() if body is not None else None,
        headers={"X-API-Key": KEY, "Content-Type": "application/json"},
    )
    try:
        with urllib.request.urlopen(req, timeout=timeout) as res:
            return json.load(res)
    except urllib.error.HTTPError as err:
        sys.exit(f"{method} {path} failed: {err.code} {err.read().decode(errors='replace')[:300]}")


def run_batch(items):
    job = call("POST", "/batch/super", {"items": items, "sources": SOURCES, "titles": TITLES})["job_id"]
    while True:
        state = call("GET", f"/batch/super/{job}?wait_seconds=25")
        if state["status"] in DONE:
            return state
        if state["status"] == "WAITING_LINKEDIN_DATA":
            print("  LinkedIn data is refreshing; checking again in 5 minutes")
            time.sleep(300)


def main():
    if len(sys.argv) != 3:
        sys.exit(__doc__)
    if not KEY:
        sys.exit("Set LISTMINER_API_KEY first. Get a key at https://listminer.com/signup")

    with open(sys.argv[1], newline="", encoding="utf-8-sig") as f:
        sites = [
            {"url": row["website"].strip(), "company_name": (row.get("company_name") or "").strip()}
            for row in csv.DictReader(f)
            if (row.get("website") or "").strip()
        ]
    print(f"{len(sites)} websites")

    found = spent = 0
    with open(sys.argv[2], "w", newline="", encoding="utf-8") as f:
        out = csv.DictWriter(f, fieldnames=FIELDS)
        out.writeheader()
        for start in range(0, len(sites), BATCH):
            state = run_batch(sites[start : start + BATCH])
            if state["status"] == "FAILED":
                sys.exit(f"Batch failed, nothing was charged: {state.get('error')}")
            spent += state.get("tokens_spent") or 0
            for site in state.get("results") or []:
                for line in site.get("results") or []:
                    out.writerow({
                        "website": site["url"],
                        "company_name": site.get("company_name") or "",
                        "full_name": line.get("full_name") or "",
                        "position": line.get("position") or "",
                        "email": line.get("email") or "",
                        "email_type": line.get("email_type") or "",
                        "linkedin_url": line.get("linkedin_url") or "",
                        "found_in": ", ".join(line.get("sources") or []),
                    })
                    found += 1
            f.flush()
            print(f"  {min(start + BATCH, len(sites))} of {len(sites)} websites done")

    balance = call("GET", "/batch/balance")["tokens_remained"]
    print(f"{found} rows written to {sys.argv[2]}. {spent} credits used, {balance} left.")


if __name__ == "__main__":
    main()
