import pandas as pd
import math
from caas_jupyter_tools import display_dataframe_to_user

# Load the uploaded CSV file
file_path = "/mnt/data/jmrichards-domain-pricing-list-2025-09-16.csv"
df = pd.read_csv(file_path)

# Normalize columns
df['TLD'] = df['TLD'].str.strip().str.lower()

# Baseline competitor (GoDaddy) public retail estimates (editable by Jay later)
# These are placeholders for common TLDs; others will fall back to a heuristic.
competitor_prices = {
    ".com": 20.99,
    ".net": 22.99,
    ".org": 23.99,
    ".biz": 21.99,
    ".info": 24.99,
    ".co": 29.99,
    ".ai": 199.99,
}

# Strategy:
# target_retail = min( max( wholesale*1.25 + 2, wholesale + 3 ), 0.90 * competitor_price )
# If competitor price unknown, use fallback: wholesale*1.25 + 2 (ensures margin)
# We'll encode markup as: retail = wholesale*(1+percent/100) + flat
# We'll use a global percent (10%) and compute per-TLD flat to hit target.
GLOBAL_PERCENT = 10.0

def compute_target(wholesale, tld):
    base = max(wholesale*1.25 + 2.0, wholesale + 3.0)  # reasonable margin floor
    comp = competitor_prices.get(tld)
    if comp is not None and comp > 0:
        target = min(base, comp * 0.90)  # aim ~10% below GoDaddy
    else:
        target = base
    # Never sell below wholesale + $1 buffer
    target = max(target, wholesale + 1.0)
    return round(target, 2)

rows = []
per_tld_overrides = {}

for _, r in df.iterrows():
    tld = r['TLD']
    wholesale = float(r['Registration'])
    target_retail = compute_target(wholesale, tld)
    # Solve for flat given GLOBAL_PERCENT: target = wholesale*(1+p) + flat
    flat = target_retail - wholesale*(1.0 + GLOBAL_PERCENT/100.0)
    # Ensure flat is at least 0, rounded to 2 decimals
    flat = round(max(0.0, flat), 2)
    rows.append({
        "TLD": tld,
        "Wholesale": round(wholesale, 2),
        "Competitor (est.)": competitor_prices.get(tld),
        "Target Retail (~10% under GoDaddy)": target_retail,
        f"Percent (global)": GLOBAL_PERCENT,
        "Flat (per-TLD override)": flat
    })
    per_tld_overrides[tld] = {"flat": float(flat), "percent": GLOBAL_PERCENT}

result_df = pd.DataFrame(rows)

# Save artifacts
table_path = "/mnt/data/ibrandbiz-domain-pricing-proposal-2025-09-16.csv"
result_df.to_csv(table_path, index=False)

# Generate JS config text
import json, textwrap
config = {
    "flat": 3.0,  # default fallback (won't be used for TLDs with overrides below)
    "percent": GLOBAL_PERCENT,
    "perTld": per_tld_overrides
}

config_js = textwrap.dedent(f"""
// Auto-generated per-TLD markup config (percent then flat), {pd.Timestamp.now().date()}
// Aim: ~10% under GoDaddy where known; otherwise healthy margin over wholesale.
// Place inside server/lib/markup.js and merge with your existing defaults.

const DEFAULTS = {json.dumps(config, indent=2)};

function round2(n) {{
  return Math.round((Number(n) + Number.EPSILON) * 100) / 100;
}}

function applyMarkup({{ wholesale, tld, config = {{}} }}) {{
  const merged = {{
    flat: DEFAULTS.flat,
    percent: DEFAULTS.percent,
    perTld: {{ ...DEFAULTS.perTld, ...(config.perTld || {{}}) }}
  }};
  const key = String(tld || "").toLowerCase();
  const ovr = merged.perTld[key] || {{}};
  const flat = (ovr.flat ?? merged.flat);
  const percent = (ovr.percent ?? merged.percent);
  let retail = Number(wholesale);
  if (!Number.isFinite(retail)) throw new Error("Invalid wholesale price");
  retail = retail * (1 + (Number(percent) / 100));
  retail = retail + Number(flat);
  return round2(retail);
}}

module.exports = {{ applyMarkup, DEFAULTS }};
""").strip()

config_path = "/mnt/data/markup.defaults.generated.js"
with open(config_path, "w", encoding="utf-8") as f:
    f.write(config_js)

# Display table to user
display_dataframe_to_user("IBrandBiz — Domain Pricing Proposal (~10% under GoDaddy)", result_df)

(table_path, config_path)
