# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
A script to generate doc/antora.yml from build metadata.
"""
import os
import subprocess
import re

script_dir = os.path.dirname(os.path.abspath(__file__))

def get_version_from_build_xml():
    build_xml_path = os.path.join(os.path.dirname(os.path.dirname(script_dir)), 'build.xml')
    
    try:
        with open(build_xml_path, 'r') as f:
            content = f.read()
        
        match = re.search(r'<property\s+name="base\.version"\s+value="([^"]+)"', content)
        if match:
            return match.group(1)
        
        raise ValueError("Could not find base.version property in build.xml")
    except Exception as e:
        raise RuntimeError(f"Failed to parse build.xml: {e}")

def is_release_build():
    """
    Detect if we're building from a release tag by checking if HEAD has a tag starting with 'cassandra-'.
    """
    try:
        result = subprocess.run(
            ['git', 'describe', '--tags', '--exact-match'],
            capture_output=True,
            text=True,
            check=False
        )
        if result.returncode == 0:
            tag = result.stdout.strip()
            return tag.startswith('cassandra-')
        return False
    except Exception:
        # If git is not available or any error occurs, assume release build
        return True

def main():
    version = get_version_from_build_xml()
    
    is_release = is_release_build()    
    output_path = os.path.join(os.path.dirname(script_dir), 'antora.yml')

    if version.endswith('-SNAPSHOT'):
        raise ValueError("base.version property in build.xml should not have SNAPSHOT suffix")

    if not is_release:
        parts = version.split('.')
        major = parts[0] if len(parts) > 0 else '0'
        minor = parts[1].split('-')[0] if len(parts) > 1 else '0'
        version = f"{major}.{minor}"

    with open(output_path, 'w') as f:
        f.write('# Auto-generated by gen-antora-yml.py\n')
        f.write('# Do not edit manually - regenerated by `ant gen-asciidoc`\n')
        f.write(f"name: Cassandra\n")
        f.write(f"version: '{version}'\n")
        f.write(f"display_version: '{version}'\n")
        if not is_release:
            f.write(f"prerelease: true\n")
        f.write("asciidoc:\n")
        f.write("  attributes:\n")
        f.write(f"    cass_url: http://cassandra.apache.org/\n")
        f.write(f"    cass-version: Cassandra {version}\n")
        f.write(f"    cassandra: Cassandra\n")
        f.write(f"    product: Apache Cassandra\n")
        f.write("nav:\n")
        f.write(f"- modules/ROOT/nav.adoc\n")
        f.write(f"- modules/cassandra/nav.adoc\n")

if __name__ == '__main__':
    main()
