import subprocess
import re
from typing import Tuple, List
from utils import run_sub_process, run_sub_process_without_output

def update_branch(branch):
    print(f'Updating branch {branch}')
    run_sub_process(f'git pull origin {branch}')

def get_next_tag(prefix):
    print('Updating tags')
    run_sub_process('git fetch --tags --force')
    print('Getting last tag')
    last_tag = run_sub_process(f'git tag -l {prefix}-[0-9]* | sort -V | tail -n 1')
    if last_tag:
        version = last_tag.split('-')[-1]
        return int(version) + 1
    return 1

def get_current_branch():
    print('Getting current branch')
    current_branch = run_sub_process('git rev-parse --abbrev-ref HEAD').rstrip('\n')
    print(f'Current branch {current_branch}')
    return current_branch

def create_and_push_tag(tag_name):
    print(f'Creating tag {tag_name}')
    run_sub_process(f'git tag {tag_name}')
    print(f'Pushing tag {tag_name}')
    run_sub_process(f'git push origin {tag_name}')

def save_changes(commit_message):
    print('Add and commit changes')
    run_sub_process_without_output('git add .')
    run_sub_process_without_output(f'git commit -m "{commit_message}" --no-verify')
    print('Changes commited')
    print('Pushing changes')
    current_branch = get_current_branch()
    run_sub_process_without_output(f'git push --set-upstream origin {current_branch}')
    print('Changes pushed')

def gh_login():
    run_sub_process_without_output('gh auth login')

def parse_version(branch: str) -> Tuple[int, int, int]:
    # Convierte 'v3.7.6' -> (3, 7, 6)
    match = re.match(r'v(\d+)\.(\d+)\.(\d+)', branch)
    if not match:
        return (0, 0, 0)
    return tuple(map(int, match.groups()))

def get_semver_branches() -> List[str]:
    try:
        result = subprocess.check_output(
            ["git", "for-each-ref", "--format=%(refname:short)", "refs/remotes/origin/"],
            text=True
        )
        all_branches = result.strip().split('\n')
        pattern = re.compile(r'^origin/v\d+\.\d+\.\d+$')
        semver_branches = [b.replace('origin/', '') for b in all_branches if pattern.match(b)]
        
        # sort by semver using parse_version
        sorted_branches = sorted(semver_branches, key=parse_version)
        return sorted_branches
    except subprocess.CalledProcessError as e:
        print(f"Error getting branches: {e}")
        return []

def get_staging_and_production_branches() -> Tuple[str, str]:
    print('Getting staging and production branches')
    branches = get_semver_branches()
    if len(branches) < 2:
        raise Exception("Not enough version branches to determine staging and production.")
    # The last is staging, the second to last is production
    return branches[-1], branches[-2]
