#!/usr/bin/env python3
"""Size a cold email infrastructure from a number of contacts.

    python3 sizing.py --contacts 15000 --touches 2 --cycle 2
    python3 sizing.py --sends 45000 --touches 3 --cycle 1
    python3 sizing.py --contacts 15000 --linkedin-seats 3 --lang fr

contacts x touches / cycle in months = sends per month.
sends / (sends per inbox per day x sending days), plus the reserve = inboxes.
inboxes / inboxes per domain = domains.
Every cost is a [min, max] range read from prices.json, next to this file.
The script refuses to run while a price is missing: nothing is guessed.
"""
import argparse
import json
import math
import pathlib
import sys

PRICES_PATH = pathlib.Path(__file__).parent / "prices.json"
PRICES = json.loads(PRICES_PATH.read_text())

p = argparse.ArgumentParser()
g = p.add_mutually_exclusive_group(required=True)
g.add_argument("--contacts", type=int, help="unique contacts with a verified email")
g.add_argument("--sends", type=int, help="sends per month, when the volume is imposed (checks a third-party figure)")
p.add_argument("--touches", type=float, default=2, help="emails per contact per cycle, measured on finished sequences")
p.add_argument("--cycle", type=float, default=2, help="months between two passes on the same contact")
p.add_argument("--per-inbox", type=int, default=20, help="sends per inbox per day")
p.add_argument("--days", type=int, default=22, help="sending days per month")
p.add_argument("--reserve", type=float, default=0.25, help="share of inboxes resting or warming")
p.add_argument("--per-domain", type=int, default=3, help="inboxes per domain")
p.add_argument("--no-signals", action="store_true", help="no signal sourcing line")
p.add_argument("--linkedin-seats", type=int, default=0, help="the client's own LinkedIn accounts, one sending seat each")
p.add_argument("--linkedin-rented", type=int, default=0, help="rented LinkedIn accounts, seat included: do not count them again in --linkedin-seats")
p.add_argument("--lang", choices=["en", "fr"], default="en")
a = p.parse_args()
en = a.lang == "en"

needed = [
    ("sending_tool", "monthly"), ("sending_tool", "max_sends"), ("sending_tool", "max_contacts"),
    ("inbox", "monthly"), ("domain", "yearly"), ("initial_contact", "price"),
    ("monthly_renewal", "share"), ("ai_per_contact_per_cycle", "price"),
]
if not a.no_signals:
    needed.append(("signals_monthly", "price"))
if a.linkedin_seats or a.linkedin_rented:
    needed.append(("linkedin_seat", "monthly"))
if a.linkedin_rented:
    needed.append(("linkedin_rented_account", "monthly"))
missing = [f"{k}.{f}" for k, f in needed if PRICES.get(k, {}).get(f) is None]
if missing:
    sys.exit(f"Missing prices in {PRICES_PATH.name}: {', '.join(missing)}. Fill them with a dated source, then run again.")


def r(key, field):
    v = PRICES[key][field]
    return v if isinstance(v, list) else [v, v]


sends = a.sends if a.sends else round(a.contacts * a.touches / a.cycle)
contacts = a.contacts if a.contacts else round(sends * a.cycle / a.touches)
inboxes = math.ceil(math.ceil(sends / (a.per_inbox * a.days)) * (1 + a.reserve))
domains = math.ceil(inboxes / a.per_domain)

initial_list = [contacts * x for x in r("initial_contact", "price")]
renewal = r("monthly_renewal", "share")
lines = [
    ("Sending tool", "Outil d'envoi", r("sending_tool", "monthly")),
    (f"{inboxes} inboxes", f"{inboxes} boites", [inboxes * x for x in r("inbox", "monthly")]),
    (f"{domains} domains, monthly", f"{domains} domaines, au mois", [domains * x / 12 for x in r("domain", "yearly")]),
    ("Data, replacing stale contacts", "Donnees, contacts perimes remplaces",
     [initial_list[0] * renewal[0], initial_list[1] * renewal[1]]),
    ("AI, scoring and personalization", "IA, tri et personnalisation",
     [contacts * x / a.cycle for x in r("ai_per_contact_per_cycle", "price")]),
]
if not a.no_signals:
    lines.append(("Signals", "Signaux", r("signals_monthly", "price")))
email = [sum(l[2][i] for l in lines) for i in (0, 1)]

linkedin = [0, 0]
if a.linkedin_seats or a.linkedin_rented:
    seat = r("linkedin_seat", "monthly")
    rented = r("linkedin_rented_account", "monthly") if a.linkedin_rented else [0, 0]
    linkedin = [a.linkedin_seats * seat[i] + a.linkedin_rented * (seat[i] + rented[i]) for i in (0, 1)]

setup = [initial_list[i] + domains * r("domain", "yearly")[i] + inboxes * r("inbox", "monthly")[i] for i in (0, 1)]


def fmt(v):
    lo, hi = round(v[0]), round(v[1])
    return f"{lo:,.0f}" if lo == hi else f"{lo:,.0f} {'to' if en else 'a'} {hi:,.0f}"


print(f"Contacts: {contacts:,} | {'Sends per month' if en else 'Envois par mois'}: {sends:,}"
      f" | {'Inboxes' if en else 'Boites'}: {inboxes} | {'Domains' if en else 'Domaines'}: {domains}\n")
print(f"| {'Line' if en else 'Poste'} | {'Per month' if en else 'Par mois'} |\n|---|---:|")
for l in lines:
    print(f"| {l[0] if en else l[1]} | {fmt(l[2])} |")
print(f"| **{'Email total' if en else 'Total email'}** | **{fmt(email)}** |")
if a.linkedin_seats or a.linkedin_rented:
    print(f"| LinkedIn | {fmt(linkedin)} |")
    print(f"| **Total** | **{fmt([email[0] + linkedin[0], email[1] + linkedin[1]])}** |")
print(f"\n{'One-off setup' if en else 'Mise en place, une fois'}: {fmt(setup)} "
      + (f"(initial list {fmt(initial_list)}, domains paid yearly, one month of inboxes warming up before sending)." if en
         else f"(liste initiale {fmt(initial_list)}, domaines a l'annee, un mois de boites en chauffe sans envoi)."))
if sends > min(r("sending_tool", "max_sends")) or contacts > min(r("sending_tool", "max_contacts")):   # plafond seul ou [min, max], le plus prudent
    print("\nWarning: above the sending tool plan ceiling, read the next tier's price at checkout.")
if a.cycle < 2:
    print("\nWarning: cycle under 2 months, the same contact is recontacted faster than the 60 to 90 day rule.")
if a.linkedin_rented:
    print("\nNote: rented LinkedIn accounts carry their own platform risk. The line exists to price a quote, not to recommend it.")
