#!/usr/bin/env python3
"""
GNature — Сервер расчётчика литража
Запуск: python3 server.py
Откройте браузер: http://localhost:8080
"""

import http.server
import json
import os
import shutil
from datetime import datetime

PORT = 8080
PARAMETERS_FILE = 'parameters.json'
BACKUP_DIR = 'backups'


class Handler(http.server.SimpleHTTPRequestHandler):

    def do_OPTIONS(self):
        self.send_response(200)
        self._cors()
        self.end_headers()

    def do_POST(self):
        if self.path == '/save':
            try:
                length = int(self.headers.get('Content-Length', 0))
                body = self.rfile.read(length)

                # Проверяем что это валидный JSON
                data = json.loads(body)

                # Делаем резервную копию перед сохранением
                if os.path.exists(PARAMETERS_FILE):
                    os.makedirs(BACKUP_DIR, exist_ok=True)
                    ts = datetime.now().strftime('%Y%m%d_%H%M%S')
                    shutil.copy(PARAMETERS_FILE, f'{BACKUP_DIR}/parameters_{ts}.json')

                # Сохраняем новый файл
                with open(PARAMETERS_FILE, 'w', encoding='utf-8') as f:
                    json.dump(data, f, ensure_ascii=False, indent=2)

                self.send_response(200)
                self._cors()
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                self.wfile.write(b'{"ok":true}')
                print(f'[{datetime.now().strftime("%H:%M:%S")}] parameters.json сохранён')

            except json.JSONDecodeError as e:
                self.send_response(400)
                self._cors()
                self.end_headers()
                self.wfile.write(f'{{"error":"Invalid JSON: {e}"}}'.encode())
            except Exception as e:
                self.send_response(500)
                self._cors()
                self.end_headers()
                self.wfile.write(f'{{"error":"{e}"}}'.encode())
                print(f'[ОШИБКА] {e}')
        else:
            self.send_error(404)

    def _cors(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')

    def end_headers(self):
        self._cors()
        super().end_headers()

    def log_message(self, format, *args):
        # Не выводим GET-запросы к статике, только важные
        if args and (str(args[0]).startswith('POST') or '404' in str(args[1])):
            print(f'[{datetime.now().strftime("%H:%M:%S")}] {format % args}')


if __name__ == '__main__':
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    print(f'GNature сервер запущен → http://localhost:{PORT}')
    print(f'Файл параметров: {os.path.abspath(PARAMETERS_FILE)}')
    print(f'Резервные копии: {os.path.abspath(BACKUP_DIR)}/')
    print('Нажмите Ctrl+C для остановки\n')
    httpd = http.server.HTTPServer(('127.0.0.1', PORT), Handler)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print('\nСервер остановлен.')
