#!/usr/bin/env python3
"""
roll_dice.py — Roll dice for The Chaos TTRPG.

Usage:
    python3 roll_dice.py <formula> [modifier]

Formulas:
    1d6       Roll 1 six-sided die
    2d6       Roll 2, sum them
    3d6       Roll 3, sum them
    2d6x10    Roll 2d6, multiply by 10
    3d6*5     Roll 3d6, multiply by 5
    odds      Roll 1d6, show success (4+) or failure (3-)
    trait N   Roll 3d6 vs trait score N — success if under

Modifier: +/- number added to total

Examples:
    python3 roll.py 1d6
    python3 roll_dice.py 3d6
    python3 roll_dice.py 2d6x10
    python3 roll_dice.py odds
    python3 roll_dice.py trait 9
    python3 roll_dice.py 1d6 +1
"""

import sys
import random
import re

def roll_dice(count, sides=6):
    return [random.randint(1, sides) for _ in range(count)]

def main():
    if len(sys.argv) < 2:
        print(__doc__.strip())
        sys.exit(1)

    formula = sys.argv[1].lower()
    modifier = 0
    if len(sys.argv) >= 3:
        try:
            modifier = int(sys.argv[2].replace('+', ''))
        except ValueError:
            pass

    if formula == 'odds':
        r = random.randint(1, 6)
        outcome = 'SUCCESS (favours character)' if r >= 4 else 'FAILURE (favours trouble)'
        print(f"  [{r}] → {outcome}")
        return

    if formula == 'trait' and len(sys.argv) >= 3:
        target = int(sys.argv[2])
        rolls = roll_dice(3)
        total = sum(rolls)
        outcome = 'SUCCESS' if total < target else 'FAILURE'
        print(f"  [{', '.join(map(str, rolls))}] = {total} vs trait {target} → {outcome}")
        return

    m = re.match(r'(\d+)d6(?:\s*([xX*])\s*(\d+))?', formula)
    if not m:
        print(f"Unknown formula: {formula}")
        sys.exit(1)

    count = int(m.group(1))
    rolls = roll_dice(count)
    total = sum(rolls) + modifier

    mult = m.group(2)
    mult_val = int(m.group(3)) if m.group(3) else 1

    if mult:
        total = total * mult_val

    label = f"×{mult_val}" if mult else ""
    mod_str = f" {'+' if modifier >= 0 else ''}{modifier}" if modifier != 0 else ""

    if count > 1:
        print(f"  [{', '.join(map(str, rolls))}] = {sum(rolls)}{mod_str}{label} → {total}")
    else:
        print(f"  [{rolls[0]}]{mod_str}{label} → {total}")

if __name__ == '__main__':
    main()
