import os
import zipfile
from io import BytesIO
from flask import Flask, render_template, request, send_file
from werkzeug.utils import secure_filename

# Get absolute path of current directory
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')

app = Flask(__name__, template_folder=TEMPLATE_DIR)
app.config['UPLOAD_FOLDER'] = os.path.join(BASE_DIR, 'uploads')
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/generate', methods=['POST'])
def generate_apk_project():
    app_name = request.form.get('app_name', 'MyApp')
    package_name = request.form.get('package_name', 'com.example.app')
    web_url = request.form.get('web_url', 'https://google.com')

    # Save Uploaded Icon
    icon_file = request.files.get('app_icon')
    icon_path = os.path.join(app.config['UPLOAD_FOLDER'], 'icon.png')
    if icon_file and icon_file.filename != '':
        icon_file.save(icon_path)

    # Generate AndroidManifest.xml
    manifest_code = f'''<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="{package_name}">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="{app_name}"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>'''

    # Generate MainActivity.java
    pkg_to_path = package_name.replace('.', '/')
    main_activity_code = f'''package {package_name};

import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {{
    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {{
        super.onCreate(savedInstanceState);
        webView = new WebView(this);
        setContentView(webView);

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);

        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("{web_url}");
    }}

    @Override
    public void onBackPressed() {{
        if (webView.canGoBack()) {{
            webView.goBack();
        }} else {{
            super.onBackPressed();
        }}
    }}
}}'''

    # Create ZIP in memory
    memory_file = BytesIO()
    with zipfile.ZipFile(memory_file, 'w', zipfile.ZIP_DEFLATED) as zip_file:
        zip_file.writestr('app/src/main/AndroidManifest.xml', manifest_code)
        zip_file.writestr(f'app/src/main/java/{pkg_to_path}/MainActivity.java', main_activity_code)
        
        if os.path.exists(icon_path):
            zip_file.write(icon_path, arcname='app/src/main/res/mipmap/ic_launcher.png')

    memory_file.seek(0)
    return send_file(
        memory_file,
        mimetype='application/zip',
        as_attachment=True,
        download_name=f'{app_name}_source.zip'
    )

if __name__ == '__main__':
    app.run(debug=True)
