#!/usr/bin/env python

"""
USAGE: lp DEFENDED TARGETS UNCLAIMED OWNED [COUNT]

DEFENDED is the letters that the enemy holds and which can not be taken.
TARGETS is the letters that the enemy holds but can be taken.
UNCLAIMED is letters nobody has played yet.
OWNED is letters you control, regardless of if they're defended or not.
COUNT is an optional number of words to suggest. Will default to 10 if absent.

The order of letters within each group is insignificant, but I find it easiest
to read from left to right and top to bottom.

If any of these groups has no letters at present, just type - in its place.

You can specify a language in your environment as LP_LANG, so for example
you could run:
  LP_LANG=de lp [letters]
"""

from __future__ import print_function, unicode_literals

import sys

import lp


if __name__ == '__main__':
    try:
        if len(sys.argv) == 6:
            count = int(sys.argv.pop(-1))
        else:
            count = 10

        _, defended, targets, unclaimed, owned = [
            a.lower() if a != '-' else '' for a in sys.argv
        ]
    except ValueError:
        doclines = __doc__.strip().split('\n')
        doclines.append(
            '\nFor example, given the following game state:\n\n' +
            lp.example_grid() +
            '\nYou would want to enter:\n  lp srm gvzsrlpdia q gnmngrendhf'
        )
        print('\n'.join(doclines))
        sys.exit(1)

    unclaimable = defended + owned
    available = targets + unclaimed + unclaimable

    if len(available) != 5 * 5:
        print('You provided {} letters. That is not a letterpress grid.'
              .format(len(available)))
        sys.exit(1)

    home = len(owned)
    away = len(targets + defended)

    unclaimed_plural = len(unclaimed) != 1

    print(
        'The current score is {home}-{away}. There {are} {unclaimed} '
        'tile{plural} left.'
        .format(
            home=home,
            away=away,
            unclaimed=len(unclaimed),
            plural='s' if unclaimed_plural else '',
            are='are' if unclaimed_plural else 'is',
        )
    )

    playable = lp.get_unique_playable_words(available)

    print('\n'.join((
        '{:>3} - {}'.format('win' if s == float('inf') else s, w)
        for w, s in
        lp.get_best_words(playable, targets, unclaimed, away-home)[:count]
    )))
