from __future__ import annotations

import argparse
import json
import sqlite3
from pathlib import Path


def main() -> None:
    parser = argparse.ArgumentParser(description="Switch local CitiFox ERP desktop settings to the hosted server.")
    parser.add_argument(
        "--sqlite",
        default=r"D:\Hermes\local\data\po_internal.sqlite3",
        help="Path to the local desktop SQLite database.",
    )
    parser.add_argument(
        "--base-url",
        default="https://texmind.xyz",
        help="Hosted API base URL.",
    )
    args = parser.parse_args()

    sqlite_path = Path(args.sqlite)
    if not sqlite_path.exists():
        raise FileNotFoundError(f"SQLite database not found: {sqlite_path}")

    base_url = str(args.base_url).strip().rstrip("/")
    payload = {
        "data_mode": "online",
        "api_base_url": base_url,
        "shared_files_base_url": f"{base_url}/shared",
        "healthcheck_path": "/health",
        "update_manifest_url": f"{base_url}/manifests/desktop.json",
        "device_name": "desktop-client",
        "auto_check_updates": True,
        "request_timeout_seconds": 8,
    }

    conn = sqlite3.connect(sqlite_path)
    try:
        conn.execute(
            """
            INSERT INTO app_settings (setting_key, value_json, updated_at)
            VALUES (?, ?, CURRENT_TIMESTAMP)
            ON CONFLICT(setting_key) DO UPDATE SET
                value_json = excluded.value_json,
                updated_at = CURRENT_TIMESTAMP
            """,
            ("server_settings", json.dumps(payload, ensure_ascii=False)),
        )
        conn.commit()
    finally:
        conn.close()

    print(json.dumps(payload, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
