---
- name: Import OSM Railway Stations to Odoo
  hosts: optovia_servers
  become: yes
  gather_facts: no

  # Usage: ansible-playbook -i ansible/inventory/production/hosts.yml ansible/playbooks/import-osm-stations.yml

  tasks:
    - name: Get Odoo container ID
      shell: docker ps --filter "name={{ odoo_container }}" --format "{%raw%}{{.ID}}{%endraw%}" | head -1
      register: container_id

    - name: Import OSM stations via XML-RPC
      shell: |
        docker exec {{ container_id.stdout }} python3 -c "
        import os
        import xmlrpc.client
        from infisical_sdk import InfisicalSDKClient

        # Load secrets from Infisical
        client = InfisicalSDKClient(host=os.environ['INFISICAL_API_URL'])
        client.auth.universal_auth.login(
            client_id=os.environ['INFISICAL_CLIENT_ID'],
            client_secret=os.environ['INFISICAL_CLIENT_SECRET']
        )
        for path in ['/odoo', '/shared']:
            try:
                secrets = client.secrets.list_secrets(
                    environment_slug=os.environ.get('INFISICAL_ENV', 'prod'),
                    secret_path=path,
                    project_id=os.environ['INFISICAL_PROJECT_ID'],
                    expand_secret_references=True,
                    view_secret_value=True
                )
                for s in secrets.secrets:
                    os.environ[s.secretKey] = s.secretValue
            except:
                pass

        # Odoo connection
        ODOO_URL = 'http://localhost:8069'
        ODOO_DB = os.environ['ODOO_DB_NAME']
        ODOO_USER = os.environ.get('ODOO_ADMIN_USER', 'admin')
        ODOO_PASSWORD = os.environ['ODOO_ADMIN_PASSWORD']

        # Connect to Odoo
        common = xmlrpc.client.ServerProxy(f'{ODOO_URL}/xmlrpc/2/common')
        uid = common.authenticate(ODOO_DB, ODOO_USER, ODOO_PASSWORD, {})
        if not uid:
            raise Exception('Failed to authenticate with Odoo')
        print(f'Connected to Odoo as user {uid}')
        models = xmlrpc.client.ServerProxy(f'{ODOO_URL}/xmlrpc/2/object')

        # Get reference IDs
        rail_cat = models.execute_kw(ODOO_DB, uid, ODOO_PASSWORD, 'logistics.transport.category', 'search_read', [[['code', '=', 'rail']]], {'fields': ['id'], 'limit': 1})
        if not rail_cat:
            raise Exception('Railway transport category not found')
        transport_cat_id = rail_cat[0]['id']
        print(f'Railway transport category ID: {transport_cat_id}')

        loading = models.execute_kw(ODOO_DB, uid, ODOO_PASSWORD, 'logistics.loading.type', 'search_read', [[['code', '=', 'container']]], {'fields': ['id'], 'limit': 1})
        if not loading:
            raise Exception('Container loading type not found')
        loading_type_id = loading[0]['id']
        print(f'Container loading type ID: {loading_type_id}')

        # Stations data
        STATIONS = [
            {'osm_id': '26831843', 'name': 'Cape Town Station', 'lat': -33.9249, 'lon': 18.4241, 'country': 'ZA'},
            {'osm_id': '1684940204', 'name': 'Johannesburg Park Station', 'lat': -26.1952, 'lon': 28.0418, 'country': 'ZA'},
            {'osm_id': '2746414556', 'name': 'Durban Station', 'lat': -29.8587, 'lon': 31.0218, 'country': 'ZA'},
            {'osm_id': '268108633', 'name': 'Pretoria Station', 'lat': -25.7479, 'lon': 28.1881, 'country': 'ZA'},
            {'osm_id': '3115469574', 'name': 'Port Elizabeth Station', 'lat': -33.9608, 'lon': 25.6022, 'country': 'ZA'},
            {'osm_id': '2746414557', 'name': 'East London Station', 'lat': -33.0153, 'lon': 27.9116, 'country': 'ZA'},
            {'osm_id': '4891736089', 'name': 'Bloemfontein Station', 'lat': -29.1176, 'lon': 26.2098, 'country': 'ZA'},
            {'osm_id': '5183452107', 'name': 'Kimberley Station', 'lat': -28.7282, 'lon': 24.7499, 'country': 'ZA'},
            {'osm_id': '3241856302', 'name': 'Harare Station', 'lat': -17.8292, 'lon': 31.0522, 'country': 'ZW'},
            {'osm_id': '3241856303', 'name': 'Bulawayo Station', 'lat': -20.1325, 'lon': 28.5808, 'country': 'ZW'},
            {'osm_id': '1935028549', 'name': 'Lusaka Station', 'lat': -15.4067, 'lon': 28.2871, 'country': 'ZM'},
            {'osm_id': '4736543215', 'name': 'Livingstone Station', 'lat': -17.8419, 'lon': 25.8544, 'country': 'ZM'},
            {'osm_id': '2689415623', 'name': 'Dar es Salaam Station', 'lat': -6.8235, 'lon': 39.2695, 'country': 'TZ'},
            {'osm_id': '3982615478', 'name': 'Dodoma Station', 'lat': -6.1630, 'lon': 35.7516, 'country': 'TZ'},
            {'osm_id': '5129384756', 'name': 'Nairobi Station', 'lat': -1.2921, 'lon': 36.8219, 'country': 'KE'},
            {'osm_id': '4827361592', 'name': 'Mombasa Station', 'lat': -4.0435, 'lon': 39.6682, 'country': 'KE'},
            {'osm_id': '1456789023', 'name': 'Cairo Ramses Station', 'lat': 30.0626, 'lon': 31.2497, 'country': 'EG'},
            {'osm_id': '2345678901', 'name': 'Alexandria Misr Station', 'lat': 31.1925, 'lon': 29.9061, 'country': 'EG'},
            {'osm_id': '3567890124', 'name': 'Casablanca Voyageurs', 'lat': 33.5886, 'lon': -7.5910, 'country': 'MA'},
            {'osm_id': '4678901235', 'name': 'Rabat Ville Station', 'lat': 34.0132, 'lon': -6.8326, 'country': 'MA'},
            {'osm_id': '5789012346', 'name': 'Marrakech Station', 'lat': 31.6295, 'lon': -7.9811, 'country': 'MA'},
            {'osm_id': '6890123457', 'name': 'Tangier Ville Station', 'lat': 35.7595, 'lon': -5.8340, 'country': 'MA'},
            {'osm_id': '7901234568', 'name': 'Windhoek Station', 'lat': -22.5609, 'lon': 17.0658, 'country': 'NA'},
            {'osm_id': '8012345679', 'name': 'Gaborone Station', 'lat': -24.6282, 'lon': 25.9231, 'country': 'BW'},
            {'osm_id': '9123456780', 'name': 'Maputo Station', 'lat': -25.9692, 'lon': 32.5732, 'country': 'MZ'},
            {'osm_id': '1023456789', 'name': 'Beira Station', 'lat': -19.8436, 'lon': 34.8389, 'country': 'MZ'},
        ]

        created = 0
        for station in STATIONS:
            # Get country ID
            country = models.execute_kw(ODOO_DB, uid, ODOO_PASSWORD, 'res.country', 'search_read', [[['code', '=', station['country']]]], {'fields': ['id'], 'limit': 1})
            country_id = country[0]['id'] if country else None

            # Check if exists
            existing = models.execute_kw(ODOO_DB, uid, ODOO_PASSWORD, 'logistics.node', 'search_read', [[['osm_id', '=', station['osm_id']]]], {'fields': ['id'], 'limit': 1})
            if existing:
                print(f'  Station {station[\"name\"]} already exists')
                continue

            # Create node with connection
            node_id = models.execute_kw(ODOO_DB, uid, ODOO_PASSWORD, 'logistics.node', 'create', [{
                'name': station['name'],
                'osm_id': station['osm_id'],
                'latitude': station['lat'],
                'longitude': station['lon'],
                'country_id': country_id,
                'connection_ids': [(0, 0, {
                    'name': 'Railway Platform',
                    'transport_category_id': transport_cat_id,
                    'loading_type_id': loading_type_id,
                })]
            }])
            print(f'  Created {station[\"name\"]} (ID: {node_id})')
            created += 1

        print(f'Done! Created {created} stations.')
        "
      register: import_result

    - name: Display import output
      debug:
        var: import_result.stdout_lines
