use std::borrow::Cow;
use std::io::Cursor;
use std::path::PathBuf;
use strafesnet_deferred_loader::loader::Loader;
use strafesnet_deferred_loader::deferred_loader::{LoadFailureMode,MeshDeferredLoader,RenderConfigDeferredLoader};
use vbsp_entities_css::Entity;

use anyhow::Result as AResult;
use futures::StreamExt;

use super::{convert_texture_to_dds,load_texture};
use super::{BspFinder,ConvertTextureError,LoadVMTError};

#[derive(clap::Subcommand)]
pub enum Commands{
	SourceToSNF(SourceToSNFSubcommand),
	ExtractTextures(ExtractTexturesSubcommand),
	VPKContents(VPKContentsSubcommand),
	BSPContents(BSPContentsSubcommand),
}

#[derive(clap::Args)]
pub struct SourceToSNFSubcommand{
	#[arg(long)]
	output_folder:PathBuf,
	#[arg(required=true)]
	input_files:Vec<PathBuf>,
	#[arg(long)]
	vpks:Vec<PathBuf>,
}
#[derive(clap::Args)]
pub struct ExtractTexturesSubcommand{
	#[arg(required=true)]
	bsp_files:Vec<PathBuf>,
	#[arg(long)]
	vpks:Vec<PathBuf>,
}
#[derive(clap::Args)]
pub struct VPKContentsSubcommand{
	#[arg(long)]
	input_file:PathBuf,
}
#[derive(clap::Args)]
pub struct BSPContentsSubcommand{
	#[arg(long)]
	input_file:PathBuf,
}

impl Commands{
	pub async fn run(self)->AResult<()>{
		match self{
			Commands::SourceToSNF(subcommand)=>source_to_snf(subcommand.input_files,subcommand.output_folder,subcommand.vpks).await,
			Commands::ExtractTextures(subcommand)=>extract_textures(subcommand.bsp_files,subcommand.vpks).await,
			Commands::VPKContents(subcommand)=>vpk_contents(subcommand.input_file),
			Commands::BSPContents(subcommand)=>bsp_contents(subcommand.input_file),
		}
	}
}

#[derive(Debug,thiserror::Error)]
enum ExtractTextureError{
	#[error("Io error {0:?}")]
	Io(#[from]std::io::Error),
	#[error("Bsp error {0:?}")]
	Bsp(#[from]vbsp::BspError),
	#[error("MeshLoad error {0:?}")]
	MeshLoad(#[from]super::loader::MeshError),
	#[error("Load VMT error {0:?}")]
	LoadVMT(#[from]LoadVMTError),
}
async fn gimme_them_textures(path:&std::path::Path,vpk_list:&[strafesnet_bsp_loader::Vpk],send_texture:tokio::sync::mpsc::Sender<(Vec<u8>,String)>)->Result<(),ExtractTextureError>{
	let bsp=vbsp::Bsp::read(tokio::fs::read(path).await?.as_ref())?;
	let loader_bsp=strafesnet_bsp_loader::Bsp::new(bsp);
	let bsp=loader_bsp.as_ref();

	let mut texture_deferred_loader=RenderConfigDeferredLoader::new();
	for texture in bsp.textures(){
		texture_deferred_loader.acquire_render_config_id(Some(Cow::Borrowed(texture.name())));
	}

	let mut mesh_deferred_loader=MeshDeferredLoader::new();
	for name in &bsp.static_props.dict.name{
		mesh_deferred_loader.acquire_mesh_id(name.as_str());
	}

	for raw_ent in &bsp.entities{
		let model=match raw_ent.parse(){
			Ok(Entity::Cycler(brush))=>brush.model,
			Ok(Entity::EnvSprite(brush))=>brush.model,
			Ok(Entity::FuncBreakable(brush))=>brush.model,
			Ok(Entity::FuncBrush(brush))=>brush.model,
			Ok(Entity::FuncButton(brush))=>brush.model,
			Ok(Entity::FuncDoor(brush))=>brush.model,
			Ok(Entity::FuncDoorRotating(brush))=>brush.model,
			Ok(Entity::FuncIllusionary(brush))=>brush.model,
			Ok(Entity::FuncMonitor(brush))=>brush.model,
			Ok(Entity::FuncMovelinear(brush))=>brush.model,
			Ok(Entity::FuncPhysbox(brush))=>brush.model,
			Ok(Entity::FuncPhysboxMultiplayer(brush))=>brush.model,
			Ok(Entity::FuncRotButton(brush))=>brush.model,
			Ok(Entity::FuncRotating(brush))=>brush.model,
			Ok(Entity::FuncTracktrain(brush))=>brush.model,
			Ok(Entity::FuncTrain(brush))=>brush.model,
			Ok(Entity::FuncWall(brush))=>brush.model,
			Ok(Entity::FuncWallToggle(brush))=>brush.model,
			Ok(Entity::FuncWaterAnalog(brush))=>brush.model,
			Ok(Entity::PropDoorRotating(brush))=>brush.model,
			Ok(Entity::PropDynamic(brush))=>brush.model,
			Ok(Entity::PropDynamicOverride(brush))=>brush.model,
			Ok(Entity::PropPhysics(brush))=>brush.model,
			Ok(Entity::PropPhysicsMultiplayer(brush))=>brush.model,
			Ok(Entity::PropPhysicsOverride(brush))=>brush.model,
			Ok(Entity::PropRagdoll(brush))=>brush.model,
			Ok(Entity::TriggerGravity(brush))=>brush.model,
			Ok(Entity::TriggerHurt(brush))=>brush.model,
			Ok(Entity::TriggerLook(brush))=>brush.model,
			Ok(Entity::TriggerMultiple(brush))=>brush.model.unwrap_or_default(),
			Ok(Entity::TriggerOnce(brush))=>brush.model,
			Ok(Entity::TriggerProximity(brush))=>brush.model,
			Ok(Entity::TriggerPush(brush))=>brush.model,
			Ok(Entity::TriggerSoundscape(brush))=>brush.model,
			Ok(Entity::TriggerTeleport(brush))=>brush.model.unwrap_or_default(),
			Ok(Entity::TriggerVphysicsMotion(brush))=>brush.model,
			Ok(Entity::TriggerWind(brush))=>brush.model,
			_=>continue,
		};
		match model.chars().next(){
			Some('*')=>(),
			_=>{
				mesh_deferred_loader.acquire_mesh_id(model);
			},
		}
	}

	let finder=BspFinder{
		bsp:&loader_bsp,
		vpks:vpk_list
	};

	let mut mesh_loader=super::loader::ModelLoader::new(finder);
	// load models and collect requested textures
	for model_path in mesh_deferred_loader.into_indices(){
		let model:vmdl::Model=match mesh_loader.load(model_path){
			Ok(model)=>model,
			Err(e)=>{
				println!("Model={model_path} Load model error: {e}");
				continue;
			},
		};
		for texture in model.textures(){
			for search_path in &texture.search_paths{
				let mut path=PathBuf::from(search_path.as_str());
				path.push(texture.name.as_str());
				let path=path.to_str().unwrap().to_owned();
				texture_deferred_loader.acquire_render_config_id(Some(Cow::Owned(path)));
			}
		}
	}

	for texture_path in texture_deferred_loader.into_indices(){
		match load_texture(finder,&texture_path){
			Ok(Some(texture))=>send_texture.send(
				(texture.into_owned(),texture_path.into_owned())
			).await.unwrap(),
			Ok(None)=>(),
			Err(e)=>println!("Texture={texture_path} Load error: {e}"),
		}
	}

	Ok(())
}

#[derive(Debug,thiserror::Error)]
enum CliConvertTextureError{
	#[error("Io error {0:?}")]
	Io(#[from]std::io::Error),
	#[error("ConvertTexture error {0:?}")]
	ConvertTexture(#[from]ConvertTextureError),
}

async fn cli_convert_texture(texture:Vec<u8>,write_file_name:impl AsRef<std::path::Path>)->Result<(),CliConvertTextureError>{
	let dds=convert_texture_to_dds(&texture)?;

	let mut dest=PathBuf::from("textures");
	dest.push(write_file_name);
	dest.set_extension("dds");
	std::fs::create_dir_all(dest.parent().unwrap())?;
	std::fs::write(&dest,&dds)?;

	Ok(())
}

async fn async_read_vpks(vpk_paths:Vec<PathBuf>,thread_limit:usize)->Vec<strafesnet_bsp_loader::Vpk>{
	futures::stream::iter(vpk_paths).map(|vpk_path|async{
		tokio::task::spawn_blocking(move||Ok::<_,vpk::Error>(strafesnet_bsp_loader::Vpk::new(vpk::VPK::read(&vpk_path)?))).await.unwrap().unwrap()
	})
	.buffer_unordered(thread_limit)
	.collect().await
}

async fn extract_textures(paths:Vec<PathBuf>,vpk_paths:Vec<PathBuf>)->AResult<()>{
	tokio::try_join!(
		tokio::fs::create_dir_all("extracted_textures"),
		tokio::fs::create_dir_all("textures"),
		tokio::fs::create_dir_all("meshes"),
	)?;
	let thread_limit=std::thread::available_parallelism()?.get();

	// load vpk list and leak for static lifetime
	let vpk_list:&[strafesnet_bsp_loader::Vpk]=async_read_vpks(vpk_paths,thread_limit).await.leak();

	let (send_texture,mut recv_texture)=tokio::sync::mpsc::channel(thread_limit);
	let mut it=paths.into_iter();
	let extract_thread=tokio::spawn(async move{
		static SEM:tokio::sync::Semaphore=tokio::sync::Semaphore::const_new(0);
		SEM.add_permits(thread_limit);
		while let (Ok(permit),Some(path))=(SEM.acquire().await,it.next()){
			let send=send_texture.clone();
			tokio::spawn(async move{
				let result=gimme_them_textures(&path,vpk_list,send).await;
				drop(permit);
				match result{
					Ok(())=>(),
					Err(e)=>println!("Map={path:?} Decode error: {e:?}"),
				}
			});
		}
	});

	// convert images
	static SEM:tokio::sync::Semaphore=tokio::sync::Semaphore::const_new(0);
	SEM.add_permits(thread_limit);
	while let (Ok(permit),Some((data,dest)))=(SEM.acquire().await,recv_texture.recv().await){
		// TODO: dedup dest?
		tokio::spawn(async move{
			let result=cli_convert_texture(data,dest).await;
			drop(permit);
			match result{
				Ok(())=>(),
				Err(e)=>println!("Convert error: {e:?}"),
			}
		});
	}
	extract_thread.await?;
	_=SEM.acquire_many(thread_limit as u32).await?;
	Ok(())
}

fn vpk_contents(vpk_path:PathBuf)->AResult<()>{
	let vpk_index=vpk::VPK::read(&vpk_path)?;
	for (label,entry) in vpk_index.tree.into_iter(){
		println!("vpk label={} entry={:?}",label,entry);
	}
	Ok(())
}

fn bsp_contents(path:PathBuf)->AResult<()>{
	let bsp=vbsp::Bsp::read(std::fs::read(path)?.as_ref())?;
	for file_name in bsp.pack.into_zip().into_inner().unwrap().file_names(){
		println!("file_name={:?}",file_name);
	}
	Ok(())
}

async fn source_to_snf(paths:Vec<PathBuf>,output_folder:PathBuf,vpk_paths:Vec<PathBuf>)->AResult<()>{
	let start=std::time::Instant::now();

	let thread_limit=std::thread::available_parallelism()?.get();

	// load vpk list and leak for static lifetime
	let vpk_list:&[strafesnet_bsp_loader::Vpk]=async_read_vpks(vpk_paths,thread_limit).await.leak();

	let mut it=paths.into_iter();
	static SEM:tokio::sync::Semaphore=tokio::sync::Semaphore::const_new(0);
	SEM.add_permits(thread_limit);

	while let (Ok(permit),Some(path))=(SEM.acquire().await,it.next()){
		let output_folder=output_folder.clone();
		tokio::spawn(async move{
			let result=match tokio::fs::read(&path).await{
				Ok(data)=>convert_to_snf(&data,vpk_list).map_err(|e|anyhow::anyhow!("{e:?}")).and_then(|snf_buf|{
					let mut dest=output_folder;
					dest.push(path.file_stem().unwrap());
					dest.set_extension("snfm");
					std::fs::write(dest,&snf_buf)?;
					Ok(())
				}),
				Err(e)=>Err(e.into()),
			};
			drop(permit);
			match result{
				Ok(())=>(),
				Err(e)=>println!("Convert error: {e:?}"),
			}
		});
	}
	_=SEM.acquire_many(thread_limit as u32).await.unwrap();

	println!("elapsed={:?}", start.elapsed());
	Ok(())
}

#[expect(dead_code)]
#[derive(Debug)]
pub enum ConvertError{
	IO(std::io::Error),
	SNFMap(strafesnet_snf::map::Error),
	BspRead(strafesnet_bsp_loader::ReadError),
	BspLoadMesh(super::loader::MeshError),
	BspLoadTexture(super::loader::TextureError),
}
impl std::fmt::Display for ConvertError{
	fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
		write!(f,"{self:?}")
	}
}
impl std::error::Error for ConvertError{}

pub fn convert_to_snf(bsp_data:&[u8],vpk_list:&[strafesnet_bsp_loader::Vpk])->Result<Vec<u8>,ConvertError>{
	const FAILURE_MODE:LoadFailureMode=LoadFailureMode::DefaultToNone;
	let bsp=strafesnet_bsp_loader::read(
		Cursor::new(bsp_data)
	).map_err(ConvertError::BspRead)?;

	let mut texture_deferred_loader=RenderConfigDeferredLoader::new();
	let mut mesh_deferred_loader=MeshDeferredLoader::new();

	let map_step1=strafesnet_bsp_loader::bsp::convert(
		&bsp,
		&mut texture_deferred_loader,
		&mut mesh_deferred_loader,
	);

	let mut mesh_loader=super::loader::MeshLoader::new(BspFinder{bsp:&bsp,vpks:vpk_list},&mut texture_deferred_loader);
	let prop_meshes=mesh_deferred_loader.into_meshes(&mut mesh_loader,FAILURE_MODE).map_err(ConvertError::BspLoadMesh)?;

	let map_step2=map_step1.add_prop_meshes(prop_meshes);

	let mut texture_loader=super::loader::TextureLoader::new();
	let render_configs=texture_deferred_loader.into_render_configs(&mut texture_loader,FAILURE_MODE).map_err(ConvertError::BspLoadTexture)?;

	let map=map_step2.add_render_configs_and_textures(render_configs);

	let mut snf_buf=Vec::new();
	strafesnet_snf::map::write_map(Cursor::new(&mut snf_buf),map).map_err(ConvertError::SNFMap)?;

	Ok(snf_buf)
}
