#!/usr/bin/env python3
"""
Finance Manager Android app generator.
Creates two separate Android projects (staff & client) with modern Kotlin + Jetpack Compose.
"""
import os, textwrap

# Common dependencies
COMPOSE_VERSION = "1.6.0"
KOTLIN_VERSION = "1.9.22"

STAFF_PACKAGE = "com.finance.staff"
CLIENT_PACKAGE = "com.finance.client"

def write(path, content):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, 'w') as f:
        f.write(textwrap.dedent(content).strip() + '\n')
    print(f"Created {path}")

def generate_project(base_dir, package, app_name, role):
    # Top-level build files
    write(f'{base_dir}/settings.gradle.kts', f"""
        rootProject.name = "{app_name}"
        include(":app")
    """)
    write(f'{base_dir}/build.gradle.kts', f"""
        plugins {{
            id("com.android.application") version "8.2.0" apply false
            id("org.jetbrains.kotlin.android") version "{KOTLIN_VERSION}" apply false
        }}
    """)
    # App build.gradle.kts
    write(f'{base_dir}/app/build.gradle.kts', f"""
        plugins {{
            id("com.android.application")
            id("org.jetbrains.kotlin.android")
        }}
        android {{
            namespace "{package}"
            compileSdk 34
            defaultConfig {{
                applicationId "{package}"
                minSdk 24
                targetSdk 34
                versionCode 1
                versionName "1.0"
            }}
            buildFeatures {{ compose true }}
            composeOptions {{ kotlinCompilerExtensionVersion = "{COMPOSE_VERSION}" }}
            compileOptions {{
                sourceCompatibility JavaVersion.VERSION_17
                targetCompatibility JavaVersion.VERSION_17
            }}
        }}
        dependencies {{
            implementation "androidx.compose.ui:ui:$COMPOSE_VERSION"
            implementation "androidx.compose.material3:material3:1.2.0"
            implementation "androidx.compose.ui:ui-tooling-preview:$COMPOSE_VERSION"
            implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.7.0"
            implementation "androidx.activity:activity-compose:1.8.2"
            implementation "com.squareup.retrofit2:retrofit:2.9.0"
            implementation "com.squareup.retrofit2:converter-gson:2.9.0"
            implementation "androidx.navigation:navigation-compose:2.7.7"
        }}
    """)
    # AndroidManifest.xml
    write(f'{base_dir}/app/src/main/AndroidManifest.xml', f"""
        <?xml version="1.0" encoding="utf-8"?>
        <manifest xmlns:android="http://schemas.android.com/apk/res/android">
            <uses-permission android:name="android.permission.INTERNET"/>
            <application
                android:allowBackup="true"
                android:label="{app_name}"
                android:supportsRtl="true"
                android:theme="@style/Theme.FinanceManager">
                <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>
    """)
    # App class
    write(f'{base_dir}/app/src/main/java/{package.replace(".","/")}/FinanceApp.kt', f"""
        package {package}
        import android.app.Application
        class FinanceApp : Application()
    """)
    # MainActivity with Compose
    write(f'{base_dir}/app/src/main/java/{package.replace(".","/")}/MainActivity.kt', f"""
        package {package}
        import android.os.Bundle
        import androidx.activity.ComponentActivity
        import androidx.activity.compose.setContent
        import androidx.compose.foundation.layout.*
        import androidx.compose.material3.*
        import androidx.compose.runtime.*
        import androidx.compose.ui.Alignment
        import androidx.compose.ui.Modifier
        import androidx.compose.ui.unit.dp
        import {package}.ui.login.LoginScreen

        class MainActivity : ComponentActivity() {{
            override fun onCreate(savedInstanceState: Bundle?) {{
                super.onCreate(savedInstanceState)
                setContent {{
                    FinanceManagerTheme {{
                        Surface(modifier = Modifier.fillMaxSize()) {{
                            LoginScreen()
                        }}
                    }}
                }}
            }}
        }}

        @Composable
        fun FinanceManagerTheme(content: @Composable () -> Unit) {{
            MaterialTheme {{
                content()
            }}
        }}
    """)
    # Login Screen
    write(f'{base_dir}/app/src/main/java/{package.replace(".","/")}/ui/login/LoginScreen.kt', f"""
        package {package}.ui.login
        import androidx.compose.foundation.layout.*
        import androidx.compose.material3.*
        import androidx.compose.runtime.*
        import androidx.compose.ui.Alignment
        import androidx.compose.ui.Modifier
        import androidx.compose.ui.unit.dp
        import {package}.data.api.RetrofitClient
        import {package}.data.api.ApiService
        import kotlinx.coroutines.launch

        @Composable
        fun LoginScreen() {{
            var username by remember {{ mutableStateOf("") }}
            var password by remember {{ mutableStateOf("") }}
            val scope = rememberCoroutineScope()
            Column(Modifier.fillMaxSize().padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {{
                Text("Finance Manager", style = MaterialTheme.typography.headlineMedium)
                Spacer(Modifier.height(32.dp))
                OutlinedTextField(value = username, onValueChange = {{ username = it }}, label = {{ Text("Username") }})
                Spacer(Modifier.height(8.dp))
                OutlinedTextField(value = password, onValueChange = {{ password = it }}, label = {{ Text("Password") }}, visualTransformation = PasswordVisualTransformation())
                Spacer(Modifier.height(16.dp))
                Button(onClick = {{
                    scope.launch {{
                        val response = RetrofitClient.api.{role}Login(username, password)
                        // handle response ...
                    }}
                }}) {{ Text("Login") }}
            }}
        }}
    """)
    # ApiService
    write(f'{base_dir}/app/src/main/java/{package.replace(".","/")}/data/api/ApiService.kt', f"""
        package {package}.data.api
        import retrofit2.Response
        import retrofit2.http.*

        interface ApiService {{
            @POST("api/{role}/login")
            suspend fun {role}Login(@Body body: Map<String, String>): Response<Map<String, Any>>
        }}
    """)
    write(f'{base_dir}/app/src/main/java/{package.replace(".","/")}/data/api/RetrofitClient.kt', f"""
        package {package}.data.api
        import retrofit2.Retrofit
        import retrofit2.converter.gson.GsonConverterFactory

        object RetrofitClient {{
            private const val BASE_URL = "http://10.0.2.2/malsat/public/"  // emulator localhost
            val api: ApiService by lazy {{
                Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()
                    .create(ApiService::class.java)
            }}
        }}
    """)

if __name__ == '__main__':
    generate_project('staff-app', STAFF_PACKAGE, "Finance Staff", "staff")
    generate_project('client-app', CLIENT_PACKAGE, "My Finance", "client")
    print("\n✅ Android projects generated! Open staff-app/ and client-app/ in Android Studio.")