use std::path::{Path,PathBuf};
use std::borrow::Cow;
use clap::{Args,Subcommand};
use anyhow::Result as AResult;
use futures::StreamExt;
use strafesnet_bsp_loader::loader::BspFinder;
use strafesnet_deferred_loader::loader::Loader;
use strafesnet_deferred_loader::deferred_loader::{LoadFailureMode,MeshDeferredLoader,RenderConfigDeferredLoader};
use vbsp_entities_css::Entity;

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

#[derive(Args)]
pub struct SourceToSNFSubcommand {
	#[arg(long)]
	output_folder:PathBuf,
	#[arg(required=true)]
	input_files:Vec<PathBuf>,
	#[arg(long)]
	vpks:Vec<PathBuf>,
}
#[derive(Args)]
pub struct ExtractTexturesSubcommand{
	#[arg(required=true)]
	bsp_files:Vec<PathBuf>,
	#[arg(long)]
	vpks:Vec<PathBuf>,
}
#[derive(Args)]
pub struct VPKContentsSubcommand {
	#[arg(long)]
	input_file:PathBuf,
}
#[derive(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),
		}
	}
}


enum VMTContent{
	VMT(String),
	VTF(String),
	Patch(vmt_parser::material::PatchMaterial),
	Unsupported,//don't want to deal with whatever vmt variant
	Unresolved,//could not locate a texture because of vmt content
}
impl VMTContent{
	fn vtf(opt:Option<String>)->Self{
		match opt{
			Some(s)=>Self::VTF(s),
			None=>Self::Unresolved,
		}
	}
}

fn get_some_texture(material:vmt_parser::material::Material)->VMTContent{
	//just grab some texture from somewhere for now
	match material{
		vmt_parser::material::Material::LightMappedGeneric(mat)=>VMTContent::vtf(Some(mat.base_texture)),
		vmt_parser::material::Material::VertexLitGeneric(mat)=>VMTContent::vtf(mat.base_texture.or(mat.decal_texture)),//this just dies if there is none
		vmt_parser::material::Material::VertexLitGenericDx6(mat)=>VMTContent::vtf(mat.base_texture.or(mat.decal_texture)),
		vmt_parser::material::Material::UnlitGeneric(mat)=>VMTContent::vtf(mat.base_texture),
		vmt_parser::material::Material::UnlitTwoTexture(mat)=>VMTContent::vtf(mat.base_texture),
		vmt_parser::material::Material::Water(mat)=>VMTContent::vtf(mat.base_texture),
		vmt_parser::material::Material::WorldVertexTransition(mat)=>VMTContent::vtf(Some(mat.base_texture)),
		vmt_parser::material::Material::EyeRefract(mat)=>VMTContent::vtf(Some(mat.cornea_texture)),
		vmt_parser::material::Material::SubRect(mat)=>VMTContent::VMT(mat.material),//recursive
		vmt_parser::material::Material::Sprite(mat)=>VMTContent::vtf(Some(mat.base_texture)),
		vmt_parser::material::Material::SpriteCard(mat)=>VMTContent::vtf(mat.base_texture),
		vmt_parser::material::Material::Cable(mat)=>VMTContent::vtf(Some(mat.base_texture)),
		vmt_parser::material::Material::Refract(mat)=>VMTContent::vtf(mat.base_texture),
		vmt_parser::material::Material::Modulate(mat)=>VMTContent::vtf(Some(mat.base_texture)),
		vmt_parser::material::Material::DecalModulate(mat)=>VMTContent::vtf(Some(mat.base_texture)),
		vmt_parser::material::Material::Sky(mat)=>VMTContent::vtf(Some(mat.base_texture)),
		vmt_parser::material::Material::Replacements(_mat)=>VMTContent::Unsupported,
		vmt_parser::material::Material::Patch(mat)=>VMTContent::Patch(mat),
		_=>unreachable!(),
	}
}

#[derive(Debug,thiserror::Error)]
enum GetVMTError{
	#[error("Bsp error {0:?}")]
	Bsp(#[from]vbsp::BspError),
	#[error("Utf8 error {0:?}")]
	Utf8(#[from]std::str::Utf8Error),
	#[error("Vdf error {0:?}")]
	Vdf(#[from]vmt_parser::VdfError),
	#[error("Vmt not found")]
	NotFound,
}

fn get_vmt(finder:BspFinder,search_name:&str)->Result<vmt_parser::material::Material,GetVMTError>{
	let vmt_data=finder.find(search_name)?.ok_or(GetVMTError::NotFound)?;
	//decode vmt and then write
	let vmt_str=core::str::from_utf8(&vmt_data)?;
	let material=vmt_parser::from_str(vmt_str)?;
	//println!("vmt material={:?}",material);
	Ok(material)
}

#[derive(Debug,thiserror::Error)]
enum LoadVMTError{
	#[error("Bsp error {0:?}")]
	Bsp(#[from]vbsp::BspError),
	#[error("GetVMT error {0:?}")]
	GetVMT(#[from]GetVMTError),
	#[error("FromUtf8 error {0:?}")]
	FromUtf8(#[from]std::string::FromUtf8Error),
	#[error("Vdf error {0:?}")]
	Vdf(#[from]vmt_parser::VdfError),
	#[error("Vmt unsupported")]
	Unsupported,
	#[error("Vmt unresolved")]
	Unresolved,
	#[error("Vmt not found")]
	NotFound,
}
fn recursive_vmt_loader<'bsp,'vpk,'a>(finder:BspFinder<'bsp,'vpk>,material:vmt_parser::material::Material)->Result<Option<Cow<'a,[u8]>>,LoadVMTError>
	where
		'bsp:'a,
		'vpk:'a,
{
	match get_some_texture(material){
		VMTContent::VMT(mut s)=>{
			s.make_ascii_lowercase();
			recursive_vmt_loader(finder,get_vmt(finder,&s)?)
		},
		VMTContent::VTF(s)=>{
			let mut texture_file_name=PathBuf::from("materials");
			texture_file_name.push(s);
			texture_file_name.set_extension("vtf");
			texture_file_name.as_mut_os_str().make_ascii_lowercase();
			Ok(finder.find(texture_file_name.to_str().unwrap())?)
		},
		VMTContent::Patch(mat)=>recursive_vmt_loader(finder,
			mat.resolve(|search_name|{
				let name_lowercase=search_name.to_lowercase();
				match finder.find(&name_lowercase)?{
					Some(bytes)=>Ok(String::from_utf8(bytes.into_owned())?),
					None=>Err(LoadVMTError::NotFound),
				}
			})?
		),
		VMTContent::Unsupported=>Err(LoadVMTError::Unsupported),
		VMTContent::Unresolved=>Err(LoadVMTError::Unresolved),
	}
}
fn load_texture<'bsp,'vpk,'a>(finder:BspFinder<'bsp,'vpk>,texture_name:&str)->Result<Option<Cow<'a,[u8]>>,LoadVMTError>
	where
		'bsp:'a,
		'vpk:'a,
{
	let mut texture_file_name=PathBuf::from("materials");
	//lower case
	texture_file_name.push(texture_name);
	texture_file_name.as_mut_os_str().make_ascii_lowercase();
	//remove stem and search for both vtf and vmt files
	let stem=texture_file_name.file_stem().unwrap().to_owned();
	texture_file_name.pop();
	texture_file_name.push(stem);
	if let Some(stuff)=finder.find(texture_file_name.to_str().unwrap())?{
		return Ok(Some(stuff));
	}

	// search for both vmt,vtf
	let mut texture_file_name_vmt=texture_file_name.clone();
	texture_file_name_vmt.set_extension("vmt");

	let get_vmt_result=get_vmt(finder,texture_file_name_vmt.to_str().unwrap());
	match get_vmt_result{
		Ok(material)=>{
			let vmt_result=recursive_vmt_loader(finder,material);
			match vmt_result{
				Ok(Some(stuff))=>return Ok(Some(stuff)),
				Ok(None)
				|Err(LoadVMTError::NotFound)=>(),
				|Err(LoadVMTError::GetVMT(GetVMTError::NotFound))=>(),
				Err(e)=>return Err(e),
			}
		}
		|Err(GetVMTError::NotFound)=>(),
		Err(e)=>Err(e)?,
	}

	// try looking for vtf
	let mut texture_file_name_vtf=texture_file_name.clone();
	texture_file_name_vtf.set_extension("vtf");

	let get_vtf_result=get_vmt(finder,texture_file_name_vtf.to_str().unwrap());
	match get_vtf_result{
		Ok(material)=>{
			let vtf_result=recursive_vmt_loader(finder,material);
			match vtf_result{
				Ok(Some(stuff))=>return Ok(Some(stuff)),
				Ok(None)
				|Err(LoadVMTError::NotFound)=>(),
				|Err(LoadVMTError::GetVMT(GetVMTError::NotFound))=>(),
				Err(e)=>return Err(e),
			}
		}
		|Err(GetVMTError::NotFound)=>(),
		Err(e)=>Err(e)?,
	}

	Ok(None)
}
#[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]strafesnet_bsp_loader::loader::MeshError),
	#[error("Load VMT error {0:?}")]
	LoadVMT(#[from]LoadVMTError),
}
async fn gimme_them_textures(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=strafesnet_bsp_loader::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 ConvertTextureError{
	#[error("Bsp error {0:?}")]
	Bsp(#[from]vbsp::BspError),
	#[error("Vtf error {0:?}")]
	Vtf(#[from]vtf::Error),
	#[error("DDS create error {0:?}")]
	DDS(#[from]image_dds::CreateDdsError),
	#[error("DDS write error {0:?}")]
	DDSWrite(#[from]image_dds::ddsfile::Error),
	#[error("Io error {0:?}")]
	Io(#[from]std::io::Error),
}

async fn convert_texture(texture:Vec<u8>,write_file_name:impl AsRef<Path>)->Result<(),ConvertTextureError>{
	let image=vtf::from_bytes(&texture)?.highres_image.decode(0)?.to_rgba8();

	let format=if image.width()%4!=0||image.height()%4!=0{
		image_dds::ImageFormat::Rgba8UnormSrgb
	}else{
		image_dds::ImageFormat::BC7RgbaUnormSrgb
	};
	//this fails if the image dimensions are not a multiple of 4
	let dds = image_dds::dds_from_image(
		&image,
		format,
		image_dds::Quality::Slow,
		image_dds::Mipmaps::GeneratedAutomatic,
	)?;

	//write dds
	let mut dest=PathBuf::from("textures");
	dest.push(write_file_name);
	dest.set_extension("dds");
	std::fs::create_dir_all(dest.parent().unwrap())?;
	let mut writer=std::io::BufWriter::new(std::fs::File::create(dest)?);
	dds.write(&mut writer)?;

	Ok(())
}

async fn read_vpks(vpk_paths:Vec<PathBuf>,thread_limit:usize)->Vec<strafesnet_bsp_loader::Vpk>{
	futures::stream::iter(vpk_paths).map(|vpk_path|async{
		// idk why it doesn't want to pass out the errors but this is fatal anyways
		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]=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=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(())
}

#[derive(Debug)]
#[expect(dead_code)]
enum ConvertError{
	IO(std::io::Error),
	SNFMap(strafesnet_snf::map::Error),
	BspRead(strafesnet_bsp_loader::ReadError),
	BspLoad(strafesnet_bsp_loader::LoadError),
}
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{}

async fn convert_to_snf(path:&Path,vpk_list:&[strafesnet_bsp_loader::Vpk],output_folder:PathBuf)->AResult<()>{
	let entire_file=tokio::fs::read(path).await?;

	let bsp=strafesnet_bsp_loader::read(
		std::io::Cursor::new(entire_file)
	).map_err(ConvertError::BspRead)?;

	let map=bsp.to_snf(LoadFailureMode::DefaultToNone,vpk_list).map_err(ConvertError::BspLoad)?;

	let mut dest=output_folder;
	dest.push(path.file_stem().unwrap());
	dest.set_extension("snfm");
	let file=std::fs::File::create(dest).map_err(ConvertError::IO)?;

	strafesnet_snf::map::write_map(file,map).map_err(ConvertError::SNFMap)?;

	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]=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=convert_to_snf(path.as_path(),vpk_list,output_folder).await;
			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(())
}
