"""The independent sources (DESIGN-independent.md section 2): records a real finance team keeps apart from the systems
that feed the warehouse, written from the generator's own records, never from an extract a fault has touched.

  deal desk   deal_desk_order_forms, deal_desk_order_form_tiers, deal_desk_discount_approvals
  pricing     pricing_rate_card
  marketing   promotion_registry
  product     product_run_events_daily (the product's own log, before metering)

Contracts, opportunities, accounts and subscriptions come from warehouse.generate.Company(seed).run(); daily run counts
come from the generator's own usage record in a clean warehouse.generate.build(seed). Every random draw here uses its
own random.Random(seed + 7001), so the generator's own draws, and the original company, are untouched.

Usage: python -B -m independent.sources <out dir> [seed]   writes the six tables as CSV
"""
from __future__ import annotations

import csv
import datetime as dt
import io
import math
import random
from decimal import Decimal
from pathlib import Path

from warehouse import generate as g

D = dt.date
SOURCE_SEED_OFFSET = 7001
GUIDE_PRICE = Decimal("250.00")          # contract seat guide price, net per seat per year (the generator's sizing rule)
P_CAP_ABOVE, CAP_STEP = 0.2, 5            # approvals: cap 5 points above the signed discount with probability 0.2
P_LOST_APPROVAL, LOST_CAPS = 0.4, (5, 10, 15, 20, 25)
FAIL_SHARE = (0.005, 0.04)                # telemetry: per-workspace share of runs that fail and are never metered
P_GAP, GAP_KEPT = 0.002, (0.50, 0.95)     # telemetry: collector outage on a workspace day keeps 50% to 95% of events
EXACT_BELOW = 50                          # failed runs drawn run by run below this many runs, else by normal approximation

COLUMNS = {
    "deal_desk_order_forms": ["contract_id", "account_id", "signed_on", "service_start", "service_end", "term_months",
                              "discount_pct", "billing_frequency", "onboarding_fee"],
    "deal_desk_order_form_tiers": ["contract_id", "tier", "tier_start", "tier_end", "licensed_seats", "annual_list_value"],
    "deal_desk_discount_approvals": ["approval_id", "opportunity_id", "account_id", "approved_on", "approved_discount_pct"],
    "pricing_rate_card": ["item_id", "item", "unit", "price_basis", "list_price", "effective_from"],
    "promotion_registry": ["coupon_id", "code", "subscription_id", "customer_id", "percent_off", "duration", "redeemed_on"],
    "product_run_events_daily": ["workspace_id", "event_date", "run_events"],
}


def licensed_seats(value: Decimal, discount: int) -> int:
    return max(5, int(value * (100 - discount) / 100 * g.SEATS_PER_CONTRACT_DOLLAR))


def failed_runs(rng: random.Random, runs: int, p: float) -> int:
    if runs < EXACT_BELOW:
        return sum(rng.random() < p for _ in range(runs))
    return max(0, min(runs, round(rng.gauss(runs * p, math.sqrt(runs * p * (1 - p))))))


def build_sources(seed: int = g.SEED, clean: dict | None = None) -> dict:
    """The six source tables for a seed. `clean` is the generator's clean build for the same seed (built here when not
    given); only its daily run counts are read, and it is never one a fault has touched."""
    co = g.Company(seed).run()
    clean = g.build(seed) if clean is None else clean
    rng = random.Random(seed + SOURCE_SEED_OFFSET)

    forms, form_tiers = [], []
    for c in co.contracts:
        forms.append({k: c[k] for k in ("contract_id", "account_id", "signed_on", "service_start", "service_end",
                                         "term_months", "discount_pct", "billing_frequency", "onboarding_fee")})
        for t in c["tiers"]:
            form_tiers.append({"contract_id": c["contract_id"], "tier": t["tier"], "tier_start": t["tier_start"],
                               "tier_end": t["tier_end"], "licensed_seats": licensed_seats(t["annual_list_value"], c["discount_pct"]),
                               "annual_list_value": t["annual_list_value"]})

    rate_card = [{"item_id": p, "item": f"{n} plan, {i}", "unit": "seat per " + ("month" if i == "monthly" else "year"),
                  "price_basis": "list", "list_price": u, "effective_from": g.SIM_START} for p, n, i, u in g.PRICES]
    rate_card += [{"item_id": "RUN", "item": "metered run", "unit": "run", "price_basis": "list", "list_price": g.RUN_PRICE,
                   "effective_from": g.SIM_START},
                  {"item_id": "CONTRACT-SEAT", "item": "contract seat guide price", "unit": "seat per year",
                   "price_basis": "net of discount", "list_price": GUIDE_PRICE, "effective_from": g.SIM_START}]

    contract_by_opp = {c["opportunity_id"]: c for c in co.contracts}
    approvals = []
    for o in co.opps:
        c = contract_by_opp.get(o["opportunity_id"])
        if o["stage"] == "closed_won" and c is not None and c["discount_pct"] > 0:
            cap = c["discount_pct"] + (CAP_STEP if rng.random() < P_CAP_ABOVE else 0)
            day = c["signed_on"] - dt.timedelta(days=rng.randint(1, 20))
        elif o["stage"] == "closed_lost" and rng.random() < P_LOST_APPROVAL:
            cap = rng.choice(LOST_CAPS)
            day = o["close_date"] - dt.timedelta(days=rng.randint(1, 20))
        else:
            continue
        approvals.append({"approval_id": f"APR-{len(approvals) + 1:04d}", "opportunity_id": o["opportunity_id"],
                          "account_id": o["account_id"], "approved_on": day, "approved_discount_pct": cap})

    registry = []
    for s in co.subs:
        if s["recurring_discount_pct"] > 0:
            registry.append({"coupon_id": f"PR-{len(registry) + 1:04d}", "code": f"LIFETIME{s['recurring_discount_pct']}",
                             "subscription_id": s["subscription_id"], "customer_id": s["customer_id"],
                             "percent_off": s["recurring_discount_pct"], "duration": "forever", "redeemed_on": s["started_on"]})

    usage = clean["tables"]["usage_daily"]
    share = {w: rng.uniform(*FAIL_SHARE) for w in sorted({r["workspace_id"] for r in usage})}
    events = []
    for r in usage:   # stored order: by day, then workspace
        n = r["runs"] + failed_runs(rng, r["runs"], share[r["workspace_id"]])
        if rng.random() < P_GAP:
            n = round(n * rng.uniform(*GAP_KEPT))
        if n > 0:
            events.append({"workspace_id": r["workspace_id"], "event_date": r["usage_date"], "run_events": n})

    return {"deal_desk_order_forms": forms, "deal_desk_order_form_tiers": form_tiers,
            "deal_desk_discount_approvals": approvals, "pricing_rate_card": rate_card,
            "promotion_registry": registry, "product_run_events_daily": events}


def link_copy(co: g.Company, close: D) -> dict[str, str]:
    """The warehouse's copy of crm_accounts at a clean close: each account created by that day that is linked, with its
    workspace (the generator's own accounts, from g.Company(seed).run())."""
    return {a["account_id"]: a["true_workspace_id"] for a in co.accounts if a["linked"] and a["created_on"] <= close}


def faulted_link_copy(tables: dict, close: D) -> dict[str, str]:
    """The copy at a close for a fault already in the data then: the faulted crm_accounts as of that day."""
    return {a["account_id"]: a["workspace_id"] for a in tables["crm_accounts"] if a["workspace_id"] and a["created_on"] <= close}


def serialize(sources: dict) -> dict[str, bytes]:
    out = {}
    for name, cols in COLUMNS.items():
        buf = io.StringIO()
        w = csv.writer(buf, lineterminator="\n")
        w.writerow(cols)
        for row in sources[name]:
            w.writerow([g.fmt(row.get(c)) for c in cols])
        out[name] = buf.getvalue().encode("utf-8")
    return out


def write(sources: dict, out: Path) -> dict[str, int]:
    out.mkdir(parents=True, exist_ok=True)
    for name, data in serialize(sources).items():
        (out / f"{name}.csv").write_bytes(data)
    return {name: len(sources[name]) for name in COLUMNS}


if __name__ == "__main__":
    import sys
    target = Path(sys.argv[1] if len(sys.argv) > 1 else "runtime/independent/sources")
    print(write(build_sources(int(sys.argv[2]) if len(sys.argv) > 2 else g.SEED), target))
