"""Usage: python csv_agent.py [sales.csv]. Amounts are integer dollars."""
import csv
from html import escape
from io import StringIO
import json
from pathlib import Path
import sys

from agent_tools import ask, execute, workspace

SAMPLE = """month,customer,revenue
September,North,1200
October,North,700
September,West,800
October,West,950
September,East,500
October,East,450
"""


def analyze(box, question, headers):
    instruction = (
        "Write a Python 3 standard-library script for the following analysis. "
        "Read /work/sales.csv with csv.DictReader. Column names are "
        f"{headers!r}. Print one JSON object mapping labels to integer dollars. "
        "Return the script in a JSON object under the key code. "
        + question
    )
    code = ask(instruction)["code"]
    box.filesystem.write_text(code, "/work/analysis.py")
    result = json.loads(execute(box, "python3", "analysis.py"))
    if not isinstance(result, dict) or not result or not all(
        type(value) is int for value in result.values()
    ):
        raise ValueError("Expected one signed integer per chart label")
    return result


def write_chart(values):
    largest = max(1, *(abs(value) for value in values.values()))
    rows = []
    for label, value in sorted(values.items(), key=lambda item: item[1]):
        width = round(100 * abs(value) / largest)
        color = "#ac4937" if value < 0 else "#367347"
        rows.append(f"<p>{escape(label)}: {value:+,} USD</p>"
                    f'<div style="width:{width}%;height:12px;background:{color}"></div>')
    Path("revenue.html").write_text("<h1>October minus September</h1>" + "".join(rows))


if __name__ == "__main__":
    data = Path(sys.argv[1]).read_text(encoding="utf-8-sig") if len(sys.argv) > 1 else SAMPLE
    headers = next(csv.reader(StringIO(data)))
    with workspace(block_network=True) as box:
        box.filesystem.write_text(data, "/work/sales.csv")
        changes = analyze(box, "For each customer, calculate October minus September. "
                          "Sum all revenue rows in each month before subtracting.", headers)
        write_chart(changes)
        print(changes)
        print(analyze(box, "Sum revenue by month for September and October across all customers.", headers))
