/*
 * RiskScape™ Copyright New Zealand Institute for Earth Science Limited
 * (Earth Sciences New Zealand) is distributed for research purposes only
 * under the terms of AGPLv3.
 *
 * RiskScape™ Copyright 2026 New Zealand Institute for Earth Science
 * Limited (Earth Sciences New Zealand). All rights reserved. Source code
 * available under the AGPLv3.
 * 
 * This program is free software: you can redistribute it and/or modify it under
 *  the terms of the GNU Affero General Public License as published by the Free
 *  Software Foundation, either version 3 of the License, or (at your option) any
 *  later version.
 * 
 * This program is distributed for RESEARCH PURPOSES ONLY, in the hope that it will
 * be useful for research and education initiatives.
 * 
 * If you are not a researcher, or you are a researcher who wishes to use this
 * program on terms other than AGPLv3 (including those who wish to restrict the
 * distribution of any source code created using this program), please contact:
 * https://riskscape.org.nz
 * 
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Affero General Public License for more details.  You should have received a copy
 * of the GNU Affero General Public License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 * 
 * By way of summary only, under the AGPLv3:
 *     • Permissions of this strongest copyleft license are conditioned
 *       on making available complete source code of licensed works and
 *       modifications, which include larger works using a licensed work,
 *       under the same license.
 *     • Copyright and license notices must be preserved.
 *     • Contributors provide an express grant of patent rights.
 *     • When a modified version is used to provide a service over a
 *       network, the complete source code of the modified version must be made
 *       available.
 */
package nz.org.riskscape.engine.typexp;

import static nz.org.riskscape.rl.TokenTypes.*;

import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;

import com.google.common.collect.ImmutableMap;

import lombok.RequiredArgsConstructor;

import nz.org.riskscape.dsl.Lexer;
import nz.org.riskscape.dsl.Token;
import nz.org.riskscape.dsl.UnexpectedTokenException;
import nz.org.riskscape.rl.TokenTypes;


/**
 * Builds an {@link AST} from a {@link Lexer}
 */
@RequiredArgsConstructor
public class Parser {

  private Lexer<TokenTypes> lexer;

  public Parser(String sourceString) {
    this.lexer = new Lexer<>(TokenTypes.tokens(), sourceString);
  }

  public Parser(Lexer<TokenTypes> lexer) {
    this.lexer = lexer;
  }

  /**
   * @return parses any possible {@link AST} from the token stream.
   */
  public AST parseAny() {

    switch (lexer.peekType()) {
    case EOF:
      return null;
    case STRING:
    case INTEGER:
    case DECIMAL:
      return parseConstant();
    case WHITESPACE:
      lexer.next();
      return parseAny();
    case IDENTIFIER:
    case QUOTED_IDENTIFIER:
    case KEY_IDENTIFIER:
      return parseTypeOrDictionary();
    default:
      throw new UnexpectedTokenException(
          EnumSet.of(STRING, INTEGER, DECIMAL, WHITESPACE, IDENTIFIER, QUOTED_IDENTIFIER, KEY_IDENTIFIER),
          lexer.peek()
      );

    }
  }

  private AST parseTypeOrDictionary() {
    switch (lexer.peekType()) {
      case KEY_IDENTIFIER:
        return parseDictionary(lexer.peek());
      default:
        return parseType();
    }
  }

  private AST.Dictionary parseDictionary(Token start) {
    ImmutableMap.Builder<AST.Symbol, AST> builder  = ImmutableMap.<AST.Symbol, AST>builder();

    // dictionary syntax is a bit kludgey - it must be the last argument in
    // the list, and is terminated by the peeked rparen (which isn't consumed
    while (lexer.peekType() != RPAREN) {
      Token identifier = lexer.expect(KEY_IDENTIFIER);
      lexer.expect(COLON);
      AST value = parseAny();

      builder.put(new AST.Symbol(identifier), value);

      if (lexer.peekType() == COMMA) {
        lexer.next();
      }
    }

    return new AST.Dictionary(start, builder.build());
  }

  private AST.Constant parseConstant() {
    Token constant = lexer.expect(STRING, INTEGER, DECIMAL);
    String raw = constant.value;
    Object nativeValue;
    switch ((TokenTypes) constant.type) {
    case STRING:
      nativeValue = raw;
      break;
    case INTEGER:
      nativeValue = Long.parseLong(raw);
      break;
    case DECIMAL:
      nativeValue = Double.parseDouble(raw);
      break;
    default:
      throw new RuntimeException("unexpected token type - " + constant);
    }
    return new AST.Constant(constant, nativeValue);
  }


  public AST parseTypeFromExpression() {
    AST parsed = parseType();
    lexer.expect(EOF);
    return parsed;
  }


  public AST parseType() {
    Token identifier = lexer.expect(IDENTIFIER, QUOTED_IDENTIFIER);

    if (lexer.peekType() == LPAREN) {
      return new AST.ComplexType(identifier, parseArgumentList());
    } else {
      return new AST.Symbol(identifier);
    }
  }

  private AST.ValueList parseArgumentList() {
    Token start = lexer.expect(LPAREN);

    List<AST> arguments = new ArrayList<>();
    while (lexer.peekType() != RPAREN) {
      arguments.add(parseAny());

      Token separator = lexer.expect(RPAREN, COMMA);
      if (separator.type == RPAREN) {
        return new AST.ValueList(start, arguments);
      }
    }

    // empty list case
    return new AST.ValueList(start, arguments);
  }
}
