#!/usr/bin/env python3
from __future__ import annotations

import json
import os
import sys
import tempfile
import urllib.error
import urllib.request
from pathlib import Path

SOURCE_URL = "https://finans.truncgil.com/today.json"
DEFAULT_OUTPUT = "/var/www/html/kurlar/kurlar.json"
REQUEST_TIMEOUT_SECONDS = 20
DIRECTORY_MODE = 0o755
FILE_MODE = 0o644


def fetch_rates(url: str) -> dict:
    request = urllib.request.Request(
        url,
        headers={
            "User-Agent": "GolderRatesUpdater/1.0",
            "Accept": "application/json",
        },
        method="GET",
    )
    with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response:
        payload = response.read()
    decoded = json.loads(payload.decode("utf-8"))
    if not isinstance(decoded, dict) or not decoded:
        raise ValueError("Kaynak JSON bos veya gecersiz.")
    return decoded


def atomic_write_json(output_path: Path, payload: dict) -> None:
    output_path.parent.mkdir(parents=True, exist_ok=True)
    try:
        os.chmod(output_path.parent, DIRECTORY_MODE)
    except OSError:
        pass
    with tempfile.NamedTemporaryFile(
        mode="w",
        encoding="utf-8",
        delete=False,
        dir=str(output_path.parent),
        suffix=".tmp",
    ) as tmp_file:
        json.dump(payload, tmp_file, ensure_ascii=False, separators=(",", ":"))
        temp_name = tmp_file.name
    os.replace(temp_name, output_path)
    try:
        os.chmod(output_path, FILE_MODE)
    except OSError:
        pass


def main() -> int:
    output_arg = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_OUTPUT
    output_path = Path(output_arg)
    try:
        payload = fetch_rates(SOURCE_URL)
        atomic_write_json(output_path, payload)
    except urllib.error.URLError as exc:
        print(f"Kur verisi alinamadi: {exc}", file=sys.stderr)
        return 1
    except (OSError, ValueError, json.JSONDecodeError) as exc:
        print(f"Kur dosyasi yazilamadi: {exc}", file=sys.stderr)
        return 1
    print(f"Kur verisi guncellendi: {output_path}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())


