#!/usr/bin/env python3
"""Atlas of Ages reference client. Python 3.10+, standard library only."""
import argparse
import json
import os
from pathlib import Path
import random
import sys
import tempfile
import time
import gzip
import urllib.error
import urllib.parse
import urllib.request
import uuid

DEFAULT_API = "https://aikeii.com/atlas-of-ages/api/v1"
DEFAULT_CREDENTIALS = Path.home() / ".config" / "atlas-of-ages" / "credentials.json"

class APIError(RuntimeError):
    def __init__(self, status, body):
        self.status, self.body = status, body
        super().__init__(f"HTTP {status}: {body.get('error', {}).get('message', 'Request failed')}")

def read_json(response):
    """Decode a JSON response, compressed or not."""
    data = response.read()
    if response.headers.get('Content-Encoding') == 'gzip':
        data = gzip.decompress(data)
    return json.loads(data)

class Client:
    def __init__(self, base=DEFAULT_API, token=None):
        self.base, self.token = base.rstrip('/'), token
        parsed = urllib.parse.urlparse(self.base)
        if parsed.scheme != 'https' and not (parsed.scheme == 'http' and parsed.hostname in ('localhost', '127.0.0.1', '::1')):
            raise ValueError('The API must use HTTPS, except for local testing.')

    def request(self, path, body=None, retry=False):
        headers = {'Accept': 'application/json', 'Accept-Encoding': 'gzip'}
        if self.token:
            headers['Authorization'] = f'Bearer {self.token}'
        encoded = None
        if body is not None:
            headers['Content-Type'] = 'application/json'
            encoded = json.dumps(body, separators=(',', ':')).encode()
        attempts = 3 if body is None or retry else 1
        for attempt in range(attempts):
            req = urllib.request.Request(self.base + path, data=encoded, headers=headers)
            try:
                with urllib.request.urlopen(req, timeout=90) as res:
                    return read_json(res)
            except urllib.error.HTTPError as error:
                try:
                    payload = read_json(error)
                except (ValueError, UnicodeError):
                    payload = {'error': {'message': 'Server returned an unreadable response.'}}
                if error.code in (502, 503, 504) and attempt + 1 < attempts:
                    time.sleep(2 ** attempt)
                    continue
                raise APIError(error.code, payload) from None
            except (urllib.error.URLError, TimeoutError, ConnectionError):
                if attempt + 1 == attempts:
                    raise
                time.sleep(2 ** attempt)

    def view(self, game):
        return self.request('/games/' + urllib.parse.quote(game, safe=''))

    def turn(self, game, view, actions=None, end=False, request_id=None):
        # Retries reuse both the revision and request ID. Never change this body
        # while retrying: a successful receipt is returned byte-for-byte.
        body = {'revision': view['game']['revision'], 'requestId': request_id or str(uuid.uuid4()),
                'actions': actions or [], 'endTurn': end}
        # Simultaneous turns: everyone's orders move the revision, so the request names its round instead.
        if view['game'].get('turnMode') == 'simultaneous': body['round'] = view['game']['round']
        return self.request('/games/' + game + '/turn', body, retry=True)

def save_credentials(path, data):
    path = Path(path).expanduser()
    path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
    fd, temporary = tempfile.mkstemp(prefix='.atlas-', dir=path.parent)
    try:
        os.fchmod(fd, 0o600)
        with os.fdopen(fd, 'w') as handle:
            json.dump(data, handle, indent=2)
            handle.write('\n')
            handle.flush()
            os.fsync(handle.fileno())
        os.replace(temporary, path)
        os.chmod(path, 0o600)
    finally:
        if os.path.exists(temporary):
            os.unlink(temporary)

def load_credentials(path):
    path = Path(path).expanduser()
    if not path.exists():
        raise RuntimeError('Register first; no credential file exists.')
    os.chmod(path, 0o600)
    return json.loads(path.read_text())

def choose_action(view, used_units):
    """A small readable policy using only the redacted view and legal options.

    Replace this function with a model or your own strategy. It receives no
    server seed, hidden tiles, opponent economies, or private event history.
    """
    options = view.get('legalActions', [])
    state = view['state']
    player_id = view['you']
    cities = [c for c in state.get('cities', []) if c['ownerId'] == player_id]
    units = [u for u in state.get('units', []) if u['ownerId'] == player_id]
    counts = {}
    for unit in units:
        counts[unit['type']] = counts.get(unit['type'], 0) + 1
    unit_by_id = {u['id']: u for u in units}
    known = {tile['id']: tile for tile in state.get('tiles', [])}
    priorities = {'found_city': 1000, 'research': 900,
                  'produce': 800, 'improve': 700, 'attack_city': 650, 'attack': 600}
    candidates = []
    for option in options:
        action = option['action']
        kind = action['type']
        score = priorities.get(kind, -1000)
        if kind == 'produce':
            project = action.get('projectId')
            desired = 'settler' if len(cities) < 4 and counts.get('settler', 0) < 1 else 'worker' if counts.get('worker', 0) < len(cities) else 'granary'
            score += 100 if project == desired else 60 if project in ('library', 'monument', 'workshop', 'market') else 0
        elif kind == 'research':
            score -= float(option.get('cost', 0)) / 100
        elif kind == 'move':
            unit = unit_by_id.get(action['unitId'], {})
            if unit.get('id') in used_units:
                continue
            score = 150 if unit.get('type') in ('scout', 'settler') else 50
            tile_id = action.get('tileId')
            score += 100 if tile_id not in known else 0
            tile = known.get(tile_id, {})
            if unit.get('type') == 'settler':
                score += 25 if tile.get('river') else 0
                score += 20 if tile.get('baseTerrain', tile.get('terrain')) in ('grassland', 'plains') else 0
            score += random.random() * 20
        elif kind == 'heal':
            unit = unit_by_id.get(action.get('unitId'), {})
            score = 550 if unit.get('hp', 0) < unit.get('maxHp', 0) else -1000
        if score > -1000:
            candidates.append((score, action))
    return max(candidates, key=lambda item: item[0])[1] if candidates else None

def roster(view):
    """One line naming every civilization and its leader, e.g. 'Genghis Khan of Mongolia (Conqueror)'."""
    players = (view.get('state') or {}).get('players') or view['game'].get('players') or []
    return '; '.join(f"{p['name']} of {p.get('civilizationName') or p.get('civilization')}" + (f" ({p['temperament']})" if p.get('temperament') else '') + (' (you)' if p['id'] == view.get('you') else '') for p in players)

def play(client, game, turns, wait, continuous):
    completed, introduced = 0, False
    while continuous or completed < turns:
        view = client.view(game)
        if not introduced and view.get('state'):
            print(f"Civilizations: {roster(view)}", flush=True); introduced = True
        if view['game']['status'] == 'finished':
            # The server deletes a finished game three days after it ends, at expiresAt (epoch milliseconds).
            # Unfinished games carry expiresAt too: thirty days after their last accepted change.
            print(json.dumps({'status': 'finished', 'victory': (view.get('state') or {}).get('victory'), 'expiresAt': view['game'].get('expiresAt')}, indent=2))
            return
        if view['game']['status'] != 'active':
            raise RuntimeError('Start the game before running the agent.')
        if view['game']['currentPlayerId'] != view['you']:
            print('Waiting for another civilization...', flush=True)
            time.sleep(wait)
            continue
        used_units = set()
        try:
            for _ in range(100):
                action = choose_action(view, used_units)
                if action is None:
                    break
                if action['type'] == 'move':
                    used_units.add(action['unitId'])
                view = client.turn(game, view, [action])
                print(f"Round {view['game']['round']}: {action['type']}", flush=True)
                if view['game']['status'] != 'active' or view['game']['currentPlayerId'] != view['you']:
                    break
            if view['game']['status'] == 'active' and view['game']['currentPlayerId'] == view['you']:
                view = client.turn(game, view, end=True)
            completed += 1
            print(f"Completed turn {completed}; game revision {view['game']['revision']}.", flush=True)
        except APIError as error:
            if error.status == 429:
                print('Rate limited; waiting one minute.', flush=True)
                time.sleep(60)
            elif error.status == 409:
                print('State changed; fetching the latest view.', flush=True)
                time.sleep(1)
            else:
                raise
        if continuous:
            time.sleep(wait)

def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--api', help='API base URL (default: saved address or public server)')
    parser.add_argument('--credentials', type=Path, default=DEFAULT_CREDENTIALS)
    commands = parser.add_subparsers(dest='command', required=True)
    register = commands.add_parser('register'); register.add_argument('name')
    create = commands.add_parser('create'); create.add_argument('name')
    create.add_argument('--seats', type=int, default=2); create.add_argument('--ai-count', type=int, default=1)
    create.add_argument('--civilization', help='civilization id or display name, e.g. dawn or Mongolia'); create.add_argument('--map-size', choices=['standard'], default='standard')
    create.add_argument('--map-style', choices=['continents'], default='continents')
    create.add_argument('--max-rounds', type=int, choices=[250], default=250)
    create.add_argument('--turn-hours', type=int, choices=[0, 24, 72], default=0); create.add_argument('--public', action='store_true')
    join_command = commands.add_parser('join'); join_command.add_argument('code'); join_command.add_argument('--civilization', help='civilization id or display name')
    commands.add_parser('list').add_argument('--scope', choices=['public', 'mine'], default='mine')
    for command in ('view', 'legal', 'start', 'skip', 'leave', 'cancel'):
        commands.add_parser(command).add_argument('game')
    turn = commands.add_parser('turn'); turn.add_argument('game'); turn.add_argument('--actions', default='[]')
    turn.add_argument('--actions-file', type=Path); turn.add_argument('--end', action='store_true'); turn.add_argument('--request-id'); turn.add_argument('--revision', type=int)
    runner = commands.add_parser('play'); runner.add_argument('game'); runner.add_argument('--turns', type=int, default=1)
    runner.add_argument('--wait', type=float, default=15); runner.add_argument('--continuous', action='store_true')
    args = parser.parse_args(argv)
    if args.command == 'register':
        if args.credentials.expanduser().exists():
            raise RuntimeError('Credential file already exists. Choose a different --credentials path for a new identity.')
        base = args.api or DEFAULT_API
        response = Client(base).request('/players', {'name': args.name})
        save_credentials(args.credentials, {'api': base, **response})
        print(json.dumps({'player': response['player'], 'credentials': str(args.credentials.expanduser())}, indent=2))
        return
    credentials = load_credentials(args.credentials)
    client = Client(args.api or credentials.get('api', DEFAULT_API), credentials['token'])
    if args.command == 'create':
        body = {'name': args.name, 'seats': args.seats, 'aiCount': args.ai_count, 'mapSize': args.map_size, 'mapStyle': args.map_style,
                'maxRounds': args.max_rounds, 'turnHours': args.turn_hours, 'visibility': 'public' if args.public else 'unlisted'}
        if args.civilization: body['civilization'] = args.civilization
        result = client.request('/games', body)
    elif args.command == 'join':
        body = {'code': args.code}
        if args.civilization: body['civilization'] = args.civilization
        result = client.request('/games/join', body)
    elif args.command == 'list':
        result = client.request('/games?scope=' + args.scope)
    elif args.command == 'play':
        if args.turns < 1 or args.wait < 1:
            raise RuntimeError('--turns and --wait must be at least 1.')
        return play(client, args.game, args.turns, args.wait, args.continuous)
    else:
        view = client.view(args.game)
        if args.command == 'view': result = view
        elif args.command == 'legal': result = view['legalActions']
        elif args.command == 'turn':
            actions = json.loads(args.actions_file.read_text() if args.actions_file else args.actions)
            if not isinstance(actions, list) or len(actions) > 24:
                raise RuntimeError('Actions must be a JSON array containing at most 24 commands.')
            if args.revision is not None: view['game']['revision'] = args.revision
            result = client.turn(args.game, view, actions, args.end, args.request_id)
        else:
            result = client.request('/games/' + args.game + '/' + args.command, {'revision': view['game']['revision']})
    print(json.dumps(result, indent=2))

if __name__ == '__main__':
    try:
        main()
    except (APIError, RuntimeError, ValueError, OSError, urllib.error.URLError) as error:
        print(str(error), file=sys.stderr)
        sys.exit(1)
    except KeyboardInterrupt:
        sys.exit(130)
