import requests
import os
from dotenv import load_dotenv
from .cipher import encrypt_message, decrypt_message
from .file_utils import read_task, write_response

load_dotenv()

DEFAULT_SERVER_URL = "https://api.your-domain.com/v1/solve"

class MathCalculator:
    @staticmethod
    def solve():
        server_url = os.getenv("MATH_CALC_SERVER_URL", DEFAULT_SERVER_URL)

        try:
            print("Reading task.txt...")
            user_prompt = read_task()

            print("Encrypting data...")
            encrypted_payload = encrypt_message(user_prompt)

            print(f"Sending request to {server_url}...")
            response = requests.post(
                server_url,
                json={"prompt": encrypted_payload},
                headers={"Content-Type": "application/json"},
                timeout=120
            )

            if response.status_code != 200:
                raise Exception(f"Server error: {response.status_code} - {response.text}")

            data = response.json()
            encrypted_response = data.get("response")

            if not encrypted_response:
                raise ValueError("Server did not return encrypted response (missing 'response' key)")

            print("Decrypting response...")
            decrypted_response = decrypt_message(encrypted_response)

            print("Writing response to task.txt...")
            write_response(decrypted_response)

            print("Done! Response successfully saved.")

        except FileNotFoundError as e:
            print(f"File error: {e}")
            raise
        except Exception as e:
            print(f"Critical error: {e}")
            raise
